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

Rod*_*ipe 3 python python-2.7

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

name = "Rodrigo"
age = 34
print f"Hello {name}, your age is {age}".format()
Run Code Online (Sandbox Code Playgroud)

虽然我知道我可以这样做:

print "Hello {name}, your age is {age}".format(name=name, age=age)
Run Code Online (Sandbox Code Playgroud)

format()将查看变量name和的范围age,将它们转换为字符串(如果可能)并粘贴到消息中。我发现这已经在 Python 3.6+ 中实现,称为Formatted String Literals。所以,我想知道(在谷歌上找不到)是否有人已经为 Python 2.7 做了类似的事情

omu*_*gru 7

您可以通过组合内置函数和字符串上的方法来尝试做事的hackish方式:localsformat

foo = "asd"
bar = "ghi"

print("{foo} and {bar}".format(**locals())
Run Code Online (Sandbox Code Playgroud)