如何使用内联变量创建多行Python字符串?

我正在寻找一种在多行Python字符串中使用变量的简洁方法.说我想做以下事情:

string1 = go
string2 = now
string3 = great

"""
I will $string1 there
I will go $string2
$string3
"""

我想看看Perl中是否有类似于$的东西来表示Python语法中的变量.

如果不是 – 用变量创建多行字符串的最简洁方法是什么?

解决方法:

常见的方法是format()函数:

>>> 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'

与您提出的问题(就语法而言)最接近的是template strings.例如:

>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'

我应该补充一点,format()函数更常见,因为它很容易获得并且不需要导入行.

上一篇:在Eclipse中粘贴多行Java字符串


下一篇:python – 使用shlex拆分多行字符串并保留引号字符