Python中是否有类似Ruby的字符串插值?
Ruby 示例:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
我觉得成功的 Python 字符串连接看起来有点啰嗦。
相关问题:
9 个回答
32
我开发了一个叫做 interpy 的工具包,它可以让你在Python中使用字符串插值。
你只需要通过 pip install interpy 来安装它。然后,在你的文件开头加上这一行 # coding: interpy!
举个例子:
#!/usr/bin/env python
# coding: interpy
name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n#{name}."
151
自从Python 2.6.X版本开始,你可能想要使用:
"my {0} string: {1}".format("cool", "Hello there!")
437
Python 3.6将会加入一种叫做“字面字符串插值”的新功能,这个功能和Ruby中的字符串插值很像。从这个版本开始(预计在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中,可以使用%运算符来进行字符串插值。第一个操作数是要插入的字符串,第二个操作数可以是不同类型的,包括一个“映射”,它将字段名称映射到要插入的值。在这里,我使用了本地变量的字典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"))