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

时间:2017-08-18 13:09:33

标签: python python-2.7

在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做了类似的事情,我想知道(无法找到谷歌搜索)

2 个答案:

答案 0 :(得分:3)

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

foo = "asd"
bar = "ghi"

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

答案 1 :(得分:1)

这是一个自动插入变量的实现。请注意,它不支持python 3 f-strings所具有的任何更高级功能(如属性访问):

import inspect

def fformat(string):
    caller_frame = inspect.currentframe().f_back
    names = dict(caller_frame.f_globals, **caller_frame.f_locals)
    del caller_frame
    return string.format(**names)
a = 1
foo = 'bar'
print fformat('hello {a} {foo}')
# output: "hello 1 bar"
相关问题