Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 連結、繰り返し、基本的なフォーマット | Strings
Pythonのデータ型

book連結、繰り返し、基本的なフォーマット

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

メッセージを複数の要素(名前、数値、結果など)から組み立てる必要がよくあります。Python では、3つの基本的なツールが用意されています。+ は複数の文字列を結合、* は文字列の繰り返し、f-strings は値をきれいに整形します。多くの要素(例:単語のリスト)を結合する場合は、str.join を使用します。

+ を使った連結

少数の文字列を結合する場合は + を使用します。テキストと数値を組み合わせる場合は、数値を変換するか f-string を利用します。

1234567891011
# Creating a personalized game message player_first = "Alice" player_last = "Johnson" greeting = player_first + " " + player_last # "Alice Johnson" score = 10 # "Score: " + score # TypeError → number must be converted to string score_message = "Score: " + str(score) # "Score: 10" print(greeting) print(score_message)
copy

*による繰り返し

文字列に整数を掛けることで、その文字列を繰り返すことが可能。

12345
echo = "ha" * 3 # "hahaha" rule = "-" * 10 # "----------" print(echo) print(rule)
copy

"sep".join(...)による複数要素の結合

joinは、文字列のリストなどのイテラブルを結合する際に最適。

123456789
# Building a message and a log entry from list data message_parts = ["Welcome", "to", "Codefinity!"] welcome_message = " ".join(message_parts) # "Welcome to Codefinity!" log_lines = ["User ID: 42", "Status: OK", "Process: Done"] log_block = "\n".join(log_lines) # "User ID: 42\nStatus: OK\nProcess: Done" print(welcome_message) print(log_block)
copy

f-stringsによる基本的なフォーマット

f-stringは{}内の式を評価し、その結果を挿入。簡潔で型変換も自動的に処理。

1234
# Displaying a progress message for a team member name = "Ada" tasks = 3 print(f"{name} completed {tasks} tasks.") # "Ada completed 3 tasks."
copy

数値フォーマット(一般的なケース)。

123456
# Calculating the total cost of an online purchase item_price = 12.5 tax_rate = 0.2 total_cost = item_price * (1 + tax_rate) print(f"Total to pay: ${total_cost:.2f}") # Rounded to 2 decimal places, e.g. "Total to pay: $15.00"
copy

リテラルの中括弧が必要な場合は、2つ重ねて記述。

1
print(f"Use {{}} for placeholders.") # "Use {} for placeholders."
copy
Note
注意

大きな文字列を作成する長いループでは、部分文字列を集めてから ''.join(pieces) を使用。

1. items = ["red", "green", "blue"] があるとき、"red, green, blue" を生成する最適な方法はどれですか?

2. "ha" * 2 + "!" は何を出力しますか?

3. total = 7.5 の場合、価格を小数点以下2桁で表示する行はどれですか?

question mark

items = ["red", "green", "blue"] があるとき、"red, green, blue" を生成する最適な方法はどれですか?

正しい答えを選んでください

question mark

"ha" * 2 + "!" は何を出力しますか?

正しい答えを選んでください

question mark

total = 7.5 の場合、価格を小数点以下2桁で表示する行はどれですか?

正しい答えを選んでください

すべて明確でしたか?

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

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

セクション 3.  5

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 3.  5
some-alt