注意 : 在 Python 中进行字符串格式化的推荐方法是使用 format(),如 公认的答案所示。我将保留这个答案作为 C 样式语法的一个示例,它也是受支持的。
# NOTE: format() is a better choice!
string1 = "go"
string2 = "now"
string3 = "great"
s = """
I will %s there
I will go %s
%s
""" % (string1, string2, string3)
print(s)
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
它适用于多行格式的字符串:
>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.
还可以传递带有变量的 dictionary:
>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
>>> string1 = "go"
>>> string2 = "now"
>>> string3 = "great"
>>> mystring = """
... I will {string1} there
... I will go {string2}
... {string3}
... """
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
>>> print(mystring.format(**locals()))
I will go there
I will go now
great
dict = {'string1': 'go',
'string2': 'now',
'string3': 'great'}
multiline_string = '''I'm will {string1} there
I will go {string2}
{string3}'''.format(**dict)
print(multiline_string)