ray88’s diary

お仕事で困ったとき用の自分用の覚書

Python 文字列に値を埋め込む(数値の埋込も可)formatメソッド 、f{値}①

python 目次 - ray88’s diary
■文字列に引数の値を埋め込む

#文字列を設定
str_sample = "チューリップは{}と{}と{}でした"
answer = str_sample.format("赤","青","黄色")
print("値代入後文字列:" + answer)

出力結果

■埋め込む値に数値がある場合
 ※引数に文字列、整数、浮動小数点が含まれる場合。数値を文字列に変換しなくても文字列に埋め込み可能

#変数に値設定
name = "高橋"
age = 23
point = 102.5
#文字列を設定
str_sample = "{}選手、年齢{}、得点{}でした"
answer = str_sample.format(name,age,point)
print("値代入後文字列:" + answer)


■引数の順番を指定して値を代入する

#変数に値設定
name = "高橋"
age = 23
point = 102.5
#文字列を設定
str_sample = "得点{2}、{0}、{1}歳"
answer = str_sample.format(name,age,point)
print("値代入後文字列:" + answer)


■キーワードで値を代入する

#文字列を設定
str_sample = "{name}選手、年齢{age}、得点{point}でした"
answer = str_sample.format(name="高橋",age=23,point=102.5)
print("値代入後文字列:" + answer)


■f{値}の書式で文字列に値を埋め込む

#変数に値を代入
name = "高橋"
age = 23
point = 102.5
#文字列を設定
text = f"{name}選手、年齢{age}、得点{point}でした"
#出力結果
print(text)