如何使用Python轻松地将变量扩展为字符串?

Lio*_*nel 13 python string variables expand idioms

这样做的好习惯是什么:

代替: print "%s is a %s %s that %s" % (name, adjective, noun, verb)

我希望能够做一些事情: print "{name} is a {adjective} {noun} that {verb}"

小智 21

"{name} is a {adjective} {noun} that {verb}".format(**locals())
Run Code Online (Sandbox Code Playgroud)
  • locals() 提供对当前命名空间的引用(作为字典).
  • **locals()将该字典解压缩为关键字参数(f(**{'a': 0, 'b': 1})f(a=0, b=1)).
  • .format()"新的字符串格式",它可以做更多的事情(例如{0.name},对于第一个位置参数的name属性).

或者,string.template(再次,如果你想避免冗余的{'name': name, ...}字典文字,请与本地人一起).

  • 有关更多详细信息和选项:http://docs.python.org/library/stdtypes.html#string-formatting (3认同)

ant*_*tam 8

从 Python 3.6 开始,您现在可以使用这种称为 f-strings 的语法,这与您 9 年前的建议非常相似

print(f"{name} is a {adjective} {noun} that {verb}")
Run Code Online (Sandbox Code Playgroud)

f-strings 或格式化的字符串文字将使用它们所用范围中的变量或其他有效的 Python 表达式。

print(f"1 + 1 = {1 + 1}")  # prints "1 + 1 = 2"
Run Code Online (Sandbox Code Playgroud)


bgp*_*ter 5

使用 string.Template

>>> 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'
Run Code Online (Sandbox Code Playgroud)