>>> 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.
还可以传递包含变量的字典:
>>> 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'
# 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)
常用的方法是
format()
函数:它可以很好地处理多行格式字符串:
还可以传递包含变量的字典:
最接近你所要求的(在语法方面)是template strings。例如:
不过,我要补充的是,
format()
函数更常见,因为它很容易使用,而且不需要导入行。注意:在Python中进行字符串格式化的推荐方法是使用
format()
,如the accepted answer中所述。我将这个答案作为也支持的C风格语法的一个例子。一些阅读:
可以对multi-line或长单行字符串中的变量使用Python 3.6's f-strings。可以使用
\n
手动指定换行符。多行字符串中的变量
长单行字符串中的变量
或者,也可以创建带有三个引号的多行f-string。
相关问题 更多 >
编程相关推荐