7 つの方法で文字列を結合する

  1. 加算演算子「+」を使用しています
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result)  # Output: Hello World
  1. コンマ区切り文字列
str1 = "Hello"
str2 = "World"
print(str1, str2)  # Output: Hello World
  1. 文字列の結合に join() メソッドを活用する
str1 = "Hello"
str2 = "World"
result = " ".join([str1, str2])
print(result)  # Output: Hello World
  1. f-stringで文字列をフォーマットする
str1 = "Hello"
str2 = "World"
result = f"{str1} {str2}"
print(result)  # Output: Hello World
  1. 文字列の書式メソッドを使用して
str1 = "Hello"
str2 = "World"
result = "{} {}".format(str1, str2)
print(result)  # Output: Hello World
  1. 文字列の % フォーマットを用いる
str1 = "Hello"
str2 = "World"
result = "%s %s" % (str1, str2)
print(result)  # Output: Hello World
  1. リスト内包表記と文字列のjoin()メソッドを活用
str1 = "Hello"
str2 = "World"
result = " ".join([word for word in [str1, str2]])
print(result)  # Output: Hello World
bannerAds