Python 以字符串形式输出变量值

Python 以字符串形式输出变量值,python,string,Python,String,在Ruby中,我可以做到这一点: "This is a string with the value of #{variable} shown." 如何在Python中实现同样的功能?现代/首选的方法是使用: 下面是一个演示: >>> 'abc{}'.format(123) 'abc123' >>> 请注意,在2.7之前的Python版本中,需要对格式字段进行显式编号: "This is a string with the value of {0} show

在Ruby中,我可以做到这一点:

"This is a string with the value of #{variable} shown."

如何在Python中实现同样的功能?

现代/首选的方法是使用:

下面是一个演示:

>>> 'abc{}'.format(123)
'abc123'
>>>
请注意,在2.7之前的Python版本中,需要对格式字段进行显式编号:

"This is a string with the value of {0} shown.".format(variable)

你有很多选择

"This is a string with the value of " + str(variable) + " shown."

"This is a string with the value of %s shown." % (str(variable))

"This is a string with the value of {0} shown.".format(variable)

这也是我们可以做到的方法之一

from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')

@C.B.:实际上是2.7以上。@MartjinPieters真的吗?我在2.7上试过了,但它给我带来了错误。也许2.6也很好,但对于他的特殊例子来说可能有点过头了。@TheSoundDefense我认为答案和你一样,但你的速度很快。先做,或者做不同的事情:
from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')