Python 是否做类似于“string #{var}"的变量插值?在红宝石?
问题描述:
在Python中,写起来很乏味:
In Python, it is tedious to write:
print "foo is" + bar + '.'
我可以在 Python 中做这样的事情吗?
Can I do something like this in Python?
打印foo is #{bar}."
答
Python 3.6+ 确实有变量插值 - 在字符串前添加 f
:
Python 3.6+ does have variable interpolation - prepend an f
to your string:
f"foo is {bar}"
对于低于此 (Python 2 - 3.5) 的 Python 版本,您可以使用 str.format
传入变量:
For versions of Python below this (Python 2 - 3.5) you can use str.format
to pass in variables:
# 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})