在Python中,写起来很繁琐:
print "foo is" + bar + '.'
我能在Python中像这样做吗?
print "foo is #{bar}."
在Python中,写起来很繁琐:
print "foo is" + bar + '.'
我能在Python中像这样做吗?
print "foo is #{bar}."
Python 3.6+ 中确实有变量插值功能 - 在字符串前加上f
:
f"foo is {bar}"
对于 Python 版本低于此版本(Python 2 - 3.5),你可以使用 str.format
来传递变量:
# Rather than this:
print("foo is #{bar}")
# You would do this:
print("foo is {}".format(bar))
# Or this:
print("foo is {bar}".format(bar=bar))
# Or this:
print("foo is %s" % (bar, ))
# Or even this:
print("foo is %(bar)s" % {"bar": bar})
print "foo is %(bar)s" % locals()
来输出。 - Brian M. HuntPython 3.6现在已经支持使用f-strings进行字面字符串插值了:
print(f"foo is {bar}.")
rf"foo is {bar}"
。 - Toni SučićPython 3.6引入了f字符串:
print(f"foo is {bar}.")
New answer:
自 Python 3.2 版本以来,str.format_map
可与 locals()
或 globals()
结合使用,可以快速地实现:
Python 3.3.2+ (default, Feb 28 2014, 00:52:16)
>>> bar = "something"
>>> print("foo is {bar}".format_map(locals()))
foo is something
>>>
我从Python Essential Reference中学习到了以下编程技巧:
>>> bar = "baz"
>>> print "foo is {bar}.".format(**vars())
foo is baz.
当我们想在格式化字符串中引用许多变量时,这非常有用:
"{x}{y}".format(x=x, y=y)
和"%(x)%(y)" % {"x": x, "y": y}
)进行比较。"{}{}".format(x, y)
、"{0}{1}".format(x, y)
和"%s%s" % (x, y)
)进行比较。"HTTP error: {error.code} {error.msg}".format(**vars())
。但是,对于format(**locals())
则不起作用。 - Mike T>>> bar = 1
>>> print "foo is {}.".format(bar)
foo is 1.
在Ruby中,以下两种写法有很大区别:
print "foo is #{bar}."
并且这些是Python中的:
print "foo is {bar}".format(bar=bar)
bar
被评估bar
只是字典的一个键print(f"foo is #{bar}")
。 - smcialpha = 123 print '答案是 {alpha}'.format(**locals())
是的,绝对没错。在我看来,Python 对字符串格式化、替换和运算符有很好的支持。
这可能会有所帮助:
http://docs.python.org/library/stdtypes.html#string-formatting-operations
你也可以像这样使用 模板字符串:
from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')
# 'tim likes kung pao'
当你想要预先构建字符串模板并在其他地方注入变量时,这非常有效。
另请参阅: PEP 292 – 更简单的字符串替换
print("Foobar is %s%s" %('Foo','bar',))