有沒有Python相當于Ruby的字符串插值?Ruby示例:name = "Spongebob Squarepants"puts "Who lives in a Pineapple under the sea? \n#{name}."成功的Python字符串連接對我來說似乎很冗長。
3 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
Python 3.6將添加類似于Ruby的字符串插值的文字字符串插值。從該版本的Python(計劃于2016年底發布)開始,您將能夠在“f-strings”中包含表達式,例如
name = "Spongebob Squarepants"print(f"Who lives in a Pineapple under the sea? {name}.")
在3.6之前,你可以得到最接近的
name = "Spongebob Squarepants"print("Who lives in a Pineapple under the sea? %(name)s." % locals())
該%
運算符可用于Python中的字符串插值。第一個操作數是要插值的字符串,第二個操作數可以有不同的類型,包括“映射”,將字段名稱映射到要插值的值。在這里,我使用局部變量字典locals()
將字段名稱映射name
為其值作為局部變量。
使用.format()
最新Python版本方法的相同代碼如下所示:
name = "Spongebob Squarepants"print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
還有string.Template
班級:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")print(tmpl.substitute(name="Spongebob Squarepants"))
添加回答
舉報
0/150
提交
取消