文字列の不変性
メニューを表示するにはスワイプしてください
Python では、文字列はイミュータブル(不変)です。一度作成された文字列の中身(文字)は、その場で変更できません。文字列を「変更」しようとすると、実際には新しい文字列が作成されます。これは、正確性(意図しないその場での編集を防ぐ)やパフォーマンス(大きな文字列の構築方法)に影響します。
インプレース編集不可
インデックスで文字を読み取ることはできますが、代入はできません。
123456s = "hello" t = "H" + s[1:] # Creates a new string: "Hello" print(t) s[0] = "H" # TypeError: strings don't support item assignment
ほとんどの文字列メソッドは新しい文字列を返し、元の文字列は変更されません。
12345678# Cleaning up user input from a registration form user_name = " Alice " user_name.strip() # returns "Alice", but the variable still has spaces print(user_name) # " Alice " user_name = user_name.strip() # assign the cleaned value back print(user_name) # "Alice" → cleaned and ready to store
ノート
.strip(): 文字列の先頭と末尾の空白を削除。
構文: string.strip()
連結は問題ありませんが、そのたびに新しいオブジェクトが生成されることに注意してください。
123456# Normalizing a user's chat message before saving it user_message = " hello\n" clean_message = user_message.strip().upper() print(user_message) # original remains " hello\n" print(clean_message) # "HELLO" → cleaned and ready for processing
ノート
.upper(): すべての文字を大文字にした文字列のコピーを返す。
構文: string.upper()
新しい文字列の作成による「変更」
スライス、replace、または連結を使用して新しい値を生成。
1234567s = "data" s = s.replace("t", "T") # "daTa" print(s) s = s[:1] + "A" + s[2:] # "dATa" print(s)
ノート
.replace(): 部分文字列のすべての出現箇所を別の部分文字列に置き換えたコピーを返す。
構文: string.replace(old, new)
効率的な構築
大きなループ内で繰り返し + を使用すると遅くなることがあります(多くの中間文字列が生成されるため)。一般的なパターンは、パーツを収集して一度だけ結合することです。
1234# Combining message parts received from a device response_parts = ["Status:", " ", "200", "\n", "Success"] response_message = "".join(response_parts) # "Status: 200\nSuccess" print(response_message)
ノート
.join():イテラブル(リストなど)の要素を、呼び出し元の文字列で区切って1つの文字列に連結します。
構文: separator.join([str, str, ...])
注記
次の章で、結合やフォーマットのパターンについてさらに学習。
1. どの行が文字列をその場で変更しようとしてエラーになるか?
2. このコードの出力は?
3. 多くの小さな部分から長い文字列を組み立てる必要があります。推奨される方法はどれですか?
すべて明確でしたか?
フィードバックありがとうございます!
セクション 3. 章 4
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 3. 章 4