Pythonにおける文字列の連結
メニューを表示するにはスワイプしてください
連結とは、2つの文字列を結合する処理。+ 演算子を使って文字列を連結でき、これは数値の加算と同様の方法。例えば、単語と冠詞を組み合わせることができるが、連結時に自動的にスペースは挿入されない。
123456789# Article and word article = "The" country = "Netherlands" # Concatenate without a space print(article + country) # Concatenate with a space between print(article + " " + country) # Add blank space between
文字列は他の文字列としか連結できない。つまり、'word' のような単語と 1 のような数値を直接連結することはできない。連結するには、数値を str(1) のように文字列へ変換する必要がある。
123456789# Variables to store the greeting message and user ID greeting = "Welcome, user #" user_id = 42 # Attempting direct concatenation (will raise an error) # print(greeting + user_id) # Correct way: Convert the number to a string print(greeting + str(user_id))
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 10
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 10