single
文字列のスライシングと連結
メニューを表示するにはスワイプしてください
文字列のスライスと連結は、Pythonにおける文字列操作の基本的なテクニックです。文字列のスライス方法や結合(連結)方法を理解することで、テキストデータを効率的に処理でき、多くのプログラミング場面で重要となります。
次のビデオでは、Alexが文字列スライスと連結の実践的な使い方を解説します。これらの概念は、効果的な文字列操作の鍵となるため、注意深くご覧ください。
文字列のスライスは、開始インデックスと終了インデックスを指定することで、大きな文字列から部分文字列を抽出する方法です。構文は string[start:end] で、start は含めたい最初の文字のインデックス、end は含めたい最後の文字の次のインデックスを指定します。このテクニックは、文字列を部分ごとに分解・分析する際に特に有用です。
使用例
スライスの仕組みを詳しく見てみましょう:
1234567fruit = "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)
連結とは、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"
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文字列は、複数の+演算子や手動での型変換を使わずにテキストと変数を組み合わせる際に特に便利。また、文字列内で数値や式のフォーマットも直接サポート。
1234567name = "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)
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文字列は、複数の変数を扱う際にも明確で簡潔、かつ読みやすい出力を実現。
12345678910111213product = "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}.")
スワイプしてコーディングを開始
食料品のリストが含まれる文字列を使います。スライスを利用して特定の単語を抽出し、これらの品物が店内のどこにあるかを明確に伝えるメッセージを作成します。
手順
-
grocery_itemsという文字列変数が与えられています。この変数には複数の食料品名が1行で記載されています。
例:"milk, eggs, cheese, bread, apples" -
文字列スライスを使って、次の品目を文字列から抽出してください:
"milk"→ 変数dairy1に格納"cheese"→ 変数dairy2に格納"bread"→ 変数bakery1に格納
-
**文字列の連結(
+)**を使い、これらの品目とその売り場番号を含む1つの文を作成してください。
出力要件
次のメッセージを出力してください:
We have dairy and bakery items: <dairy1>, <dairy2>, and <bakery1> in aisle 5
解答
フィードバックありがとうございます!
single
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください