Python 2中的格式化字符串文字


问题内容

在Python 2.7中编写模块时,我需要一种方法

name = "Rodrigo"
age = 34
print f"Hello {name}, your age is {age}".format()

尽管我知道我可以做到:

print "Hello {name}, your age is {age}".format(name=name, age=age)

format()看起来在范围变量nameage,将它们转换为字符串(如果可能的话),并粘贴到邮件。我发现这已经在Python
3.6+中实现,称为 Formatted String
Literals

。所以,我想知道(找不到谷歌搜索)是​​否有人对Python 2.7采取了类似的方法


问题答案:

您可以通过将内置函数和字符串上的方法结合 使用, 以尝试一种 黑手党 的做事方式:locals``format

foo = "asd"
bar = "ghi"

print("{foo} and {bar}".format(**locals())