红宝石示例:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功的 Python 字符串连接对我来说似乎很冗长。
Python 3.6 将添加文字字符串插值 https://www.python.org/dev/peps/pep-0498/类似于 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())
The %
运算符可用于字符串插值 http://docs.python.org/library/stdtypes.html#string-formatting-operations在Python中。第一个操作数是要插值的字符串,第二个操作数可以具有不同的类型,包括“映射”,将字段名称映射到要插值的值。这里我使用了局部变量的字典locals()
映射字段名称name
其值作为局部变量。
使用相同的代码.format()
最近的 Python 版本的方法如下所示:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
还有string.Template http://docs.python.org/library/string.html#template-strings class:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)