Ruby示例:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功的Python字符串连接对我来说似乎很冗长.
Ruby示例:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功的Python字符串连接对我来说似乎很冗长.
Python3.6将添加literal string interpolation个类似Ruby的字符串插值.从该版本的Python(计划于2016年底发布)开始,您将能够在"f字符串"中包含表达式,例如.
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中,%
运算符可以用于string interpolation.第一个操作数是要内插的字符串,第二个操作数可以有不同的类型,包括"映射",将字段名映射到要内插的值.在这里,我使用局部变量字典locals()
将字段名name
映射到其作为局部变量的值.
使用最新Python版本的.format()
方法的相同代码如下所示:
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"))