mko*_*mko 34 ruby python language-comparisons string-formatting string-interpolation
在Python中,编写它是很繁琐的:
print "foo is" + bar + '.'
Run Code Online (Sandbox Code Playgroud)
我可以在Python中做这样的事吗?
print "foo is #{bar}."
Sea*_*ira 50
Python 3.6+确实有变量插值 - f在你的字符串前加一个:
f"foo is {bar}"
Run Code Online (Sandbox Code Playgroud)
对于此下面的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})
Run Code Online (Sandbox Code Playgroud)
AXO*_*AXO 25
Python 3.6 会的有文字串插使用F-字符串:
print(f"foo is {bar}.")
Run Code Online (Sandbox Code Playgroud)
war*_*iuc 11
Python 3.6 引入了f-strings:
print(f"foo is {bar}.")
Run Code Online (Sandbox Code Playgroud)
老答案:
从版本3.2开始,Python 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
>>>
Run Code Online (Sandbox Code Playgroud)
我从Python Essential Reference学到了以下技术:
>>> bar = "baz"
>>> print "foo is {bar}.".format(**vars())
foo is baz.
Run Code Online (Sandbox Code Playgroud)
当我们想要在格式化字符串中引用许多变量时,这非常有用:
"{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))进行比较.>>> bar = 1
>>> print "foo is {}.".format(bar)
foo is 1.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27654 次 |
| 最近记录: |