Ruby的例子:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功的Python字符串连接对我来说似乎很冗长。
Ruby的例子:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功的Python字符串连接对我来说似乎很冗长。
当前回答
Python的字符串插值类似于C的printf()
如果你尝试:
name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name
标记%s将被name变量替换。您应该看一下打印功能标签:http://docs.python.org/library/functions.html
其他回答
对于旧的Python(在2.4上测试),上面的解决方案指明了方向。你可以这样做:
import string
def try_interp():
d = 1
f = 1.1
s = "s"
print string.Template("d: $d f: $f s: $s").substitute(**locals())
try_interp()
你会得到
d: 1 f: 1.1 s: s
从Python 2.6开始。X你可能想用:
"my {0} string: {1}".format("cool", "Hello there!")
Python的字符串插值类似于C的printf()
如果你尝试:
name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name
标记%s将被name变量替换。您应该看一下打印功能标签:http://docs.python.org/library/functions.html
按照PEP 498的规定,Python 3.6将包含字符串插值。你可以这样做:
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')
请注意,我讨厌海绵宝宝,所以写这篇文章有点痛苦。:)
Python 3.6及更新版本使用f-strings进行字面值字符串插值:
name='world'
print(f"Hello {name}!")