Python 文字列に変数を埋め込む

目次

確認環境:Python 3

文字列に変数を埋め込む(format)

"文字列{}".format(引数)
a = "red"
b = "blue"

print("This is {}.That is {}.".format(a, b))  #This is red.That is blue.

formatメソッドで文字列の中にある{}の中に値を埋め込みます。

文字列に変数を埋め込む(f)

f"文字列{変数}"

f文字列は値を埋め込んで文字列を結合します。

a = "red"
b = "blue"

print(f"This is {a}.That is {b}.")  #This is red.That is blue.

4行目は、先頭にfがあります。変数の値を{}の中に埋め込みます。
上記のformatメソッドより簡潔に記述できます。

文字列に変数を埋め込む(%sと%d)

"文字列 %s等 [%s等]"  % (変数[,変数])

%演算子で値を埋め込んで文字列を結合できます。

a = "red"
b = "blue"

print("%s and %s %dtypes." % (a, b, 2))  # red and blue 2types.

%sは文字列で%dは整数を表します。

%s 文字列
%d 整数

関連の記事

Python 文字列をつなげるサンプル(結合)

△上に戻る