简体   繁体   English

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

[英]Formatted String Literals in Python 2

While writing a module in Python 2.7 I had the need of a way for doing 在Python 2.7中编写模块时,我需要一种方法

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

although I know I could just do: 尽管我知道我可以做到:

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

format() would look in the scope for variables name and age , cast them to a string (if possible) and paste into the message. format()将在变量nameage的范围内查找,将它们转换为字符串(如果可能)并粘贴到消息中。 I've found that this is already implemented in Python 3.6+, called Formatted String Literals . 我发现这已在Python 3.6+中实现,称为Formatted String Literals So, I was wondering (couldn't find it googling) if anyone has made an approach to something similar for Python 2.7 因此,我想知道(找不到谷歌搜索)是​​否有人对Python 2.7采取了类似的方法

You can try the hackish way of doing things by combining the builtin locals function and the format method on the string: 您可以通过组合内置的locals函数和字符串上的format方法来尝试这种怪异的处理方式:

foo = "asd"
bar = "ghi"

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

Here's an implementation that automatically inserts variables. 这是一个自动插入变量的实现。 Note that it doesn't support any of the fancier features python 3 f-strings have (like attribute access): 请注意,它不支持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