[英]How do I use Python to easily expand variables to strings?
这样做的好习惯是什么:
而不是: print "%s is a %s %s that %s" % (name, adjective, noun, verb)
我希望能够做一些事情: print "{name} is a {adjective} {noun} that {verb}"
"{name} is a {adjective} {noun} that {verb}".format(**locals())
locals()
提供对当前命名空间的引用(作为字典)。**locals()
将该字典解包为关键字参数( f(**{'a': 0, 'b': 1})
是f(a=0, b=1)
)。.format()
是“新的字符串格式” ,顺便说一下,它可以做更多的事情(例如{0.name}
用于第一个位置参数的 name 属性)。 或者, string.template
(同样,如果您想避免冗余{'name': name, ...}
dict 文字,则使用 locals)。
从 Python 3.6 开始,您现在可以使用这种称为 f-strings 的语法,这与您 9 年前的建议非常相似😊
print(f"{name} is a {adjective} {noun} that {verb}")
f-strings 或格式化的字符串文字将使用它们所用范围中的变量或其他有效的 Python 表达式。
print(f"1 + 1 = {1 + 1}") # prints "1 + 1 = 2"
>>> from string import Template
>>> t = Template("$name is a $adjective $noun that $verb")
>>> t.substitute(name="Lionel", adjective="awesome", noun="dude", verb="snores")
'Lionel is a awesome dude that snores'
对于 python 2,请执行以下操作:
print name,'is a',adjective,noun,'that',verb
对于 python 3 添加括号:
print(name,'is a',adjective,noun,'that',verb)
如果需要将其保存为字符串,则必须与+
运算符连接,并且必须插入空格。 除非在参数末尾有尾随逗号,
否则print
在所有 处插入一个空格,在这种情况下它放弃换行符。
保存到字符串变量:
result = name+' is a '+adjective+' '+noun+' that '+verb
从 python 3.8 开始,还可以将变量名扩展为字符串,这对于日志记录和调试非常有用:
name="John Doe"
print(f"Found person {name=}")
# will print:
"Found person name='John Doe'"
# vs no variable name
print(f"Found person {name=}")
# will print:
"Found person John Doe"
注意变量后面的=
符号,它告诉格式化程序包含变量名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.