有沒(méi)有Python相當(dāng)于Ruby的字符串插值?Ruby示例:name = "Spongebob Squarepants"puts "Who lives in a Pineapple under the sea? \n#{name}."成功的Python字符串連接對(duì)我來(lái)說(shuō)似乎很冗長(zhǎng)。
3 回答

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