如何使用Python将变量轻松转换为字符串?
有什么好的说法可以做到这一点:
我不想用这种方式:
print "%s is a %s %s that %s" % (name, adjective, noun, verb)
我想用更简单的方式,比如:
print "{name} is a {adjective} {noun} that {verb}"
5 个回答
6
使用 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'
11
自从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"
- 这是格式化字符串字面量的文档链接: https://docs.python.org/3/reference/lexical_analysis.html#f-strings
- 这是正式化这个功能的PEP文档链接: https://www.python.org/dev/peps/pep-0498/
25
locals()
是一个函数,它可以让你看到当前的命名空间,简单来说就是一个字典,里面存放着当前所有的变量和它们的值。**locals()
是把这个字典里的内容拆开,变成关键字参数传给函数。比如说,f(**{'a': 0, 'b': 1})
就等于f(a=0, b=1)
。.format()
是一种新的字符串格式化方法,它可以做很多事情,比如你可以用{0.name}
来获取第一个位置参数的名字属性。
"{name} is a {adjective} {noun} that {verb}".format(**locals())
另外,你也可以使用 string.template
,如果你想避免写重复的字典,比如 {'name': name, ...}
。