Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 文字列のスライシングと連結 | 変数と型
Python入門
セクション 2.  6
single

single

book文字列のスライシングと連結

メニューを表示するにはスワイプしてください

文字列のスライス連結は、Pythonにおける文字列操作の基本的なテクニックです。文字列のスライス方法や結合(連結)方法を理解することで、テキストデータを効率的に処理でき、多くのプログラミング場面で重要となります。

次のビデオでは、Alexが文字列スライスと連結の実践的な使い方を解説します。これらの概念は、効果的な文字列操作の鍵となるため、注意深くご覧ください。

文字列のスライスは、開始インデックスと終了インデックスを指定することで、大きな文字列から部分文字列を抽出する方法です。構文は string[start:end] で、start含めたい最初の文字のインデックス、end含めたい最後の文字の次のインデックスを指定します。このテクニックは、文字列を部分ごとに分解・分析する際に特に有用です。

使用例

スライスの仕組みを詳しく見てみましょう:

1234567
fruit = "Strawberries" # Slicing the string to get "Straw" # Remember, the 'w' is indexed at 4 but if we want to include it in the slice, we need to go up to 5 sliced_fruit = fruit[0:5] print("Sliced part:", sliced_fruit)
copy

連結とは、2つ以上の文字列を末尾同士で結合し、新しい文字列を作成する操作

これは + 演算子を使って実現でき、文章全体を作成したり、整形された出力を生成したりする際に便利。

以下は、文字列を連結して新しい文字列を作成する方法

12345678
# Concatenating strings part1 = "Straw" part2 = "berry" new_word = part1 + part2 # "Strawberry" print("Concatenated word:", new_word) # If you want to separate the words with a space, you need to add " " between the two parts print(part1 + " " + part2) # "Straw berry"
copy

F文字列(F-Strings)

PythonのF文字列は、変数や式を文字列リテラル内に直接埋め込むためのシンプルかつ強力な方法。開き引用符の前にfまたはFを付けることで、中括弧({})内に変数名や式を記述でき、文字列の補間やフォーマットをより読みやすく簡潔に記述可能。

例:

name = "Alex"
age = 30
print(f"Hello, {name}! You are {age} years old.")

このコードの出力:Hello, Alex! You are 30 years old.

F文字列は、複数の+演算子や手動での型変換を使わずにテキストと変数を組み合わせる際に特に便利。また、文字列内で数値や式のフォーマットも直接サポート。

1234567
name = "Alex" age = 27 # Using an f-string to embed variables directly into the string message = f"My name is {name} and I am {age} years old." print(message)
copy

F文字列による複数変数の埋め込み

F文字列を使うことで、複数の変数や式を1つの読みやすいメッセージにまとめることが容易。開き引用符の前にfを付け、中括弧({})内に必要なだけ変数や式を挿入可能。

この方法は、複数の+演算子を使うよりもはるかに簡潔でミスが少ない。また、中括弧内に句読点やスペース、計算式も追加できる。

例:

first = "milk"
second = "cheese"
third = "bread"
aisle = 5

# Embed multiple variables in one message
message = f"We have dairy and bakery items: {first}, {second}, and {third} in aisle {aisle}"
print(message)

このコードの出力:We have dairy and bakery items: milk, cheese, and bread in aisle 5

また、中括弧内に式を記述することも可能:

count = 3
print(f"There are {count + 2} total items listed.")

F文字列は、複数の変数を扱う際にも明確で簡潔、かつ読みやすい出力を実現。

12345678910111213
product = "apples" quantity = 12 price_per_item = 0.75 total_cost = quantity * price_per_item # Using an f-string to include variables and an expression in a single message message = f"You bought {quantity} {product} at ${price_per_item} each. Total cost: ${total_cost:.2f}." print(message) # Embedding an expression directly in the f-string print(f"Half of your apples would be {quantity // 2}.")
copy
タスク

スワイプしてコーディングを開始

食料品のリストが含まれる文字列を使います。スライスを利用して特定の単語を抽出し、これらの品物が店内のどこにあるかを明確に伝えるメッセージを作成します。

手順

  1. grocery_items という文字列変数が与えられています。この変数には複数の食料品名が1行で記載されています。
    例: "milk, eggs, cheese, bread, apples"

  2. 文字列スライスを使って、次の品目を文字列から抽出してください:

    • "milk" → 変数 dairy1 に格納
    • "cheese" → 変数 dairy2 に格納
    • "bread" → 変数 bakery1 に格納
  3. **文字列の連結(+)**を使い、これらの品目とその売り場番号を含む1つの文を作成してください。

出力要件

次のメッセージを出力してください:
We have dairy and bakery items: <dairy1>, <dairy2>, and <bakery1> in aisle 5

解答

Switch to desktop実践的な練習のためにデスクトップに切り替える下記のオプションのいずれかを利用して、現在の場所から続行する
すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 2.  6
single

single

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

some-alt