繁体   English   中英

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

[英]Formatted String Literals in 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())

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

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM