在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})