目次
| 基本・最新 | 文字列に変数を埋め込む(f文字列) |
| 古い形式 | 文字列に変数を埋め込む(format) |
| 古い形式 | 文字列に変数を埋め込む(%sと%d) |
確認環境:Python 3
文字列に変数を埋め込む(f文字列)
| f"文字列{変数}" |
Python 3.6以降で最も推奨される方法です。
a = "red"
b = "blue"
print(f"This is {a}.That is {b}.") #This is red.That is blue.
先頭にfがあります。変数の値を{}の中に埋め込みます。
文字列に変数を埋め込む(format)
| "文字列{}".format(引数) |
a = "red"
b = "blue"
print("This is {}.That is {}.".format(a, b)) #This is red.That is blue.
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 | 整数 |
関連の記事
