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

2024-09-28 20:48:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种在多行Python字符串中使用变量的干净方法。假设我想做以下事情:

string1 = go
string2 = now
string3 = great

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

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

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


Tags: 方法字符串go语法事情willnowperl
3条回答

常用的方法是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()函数更常见,因为它很容易使用,而且不需要导入行。

注意:在Python中进行字符串格式化的推荐方法是使用format(),如the accepted answer中所述。我将这个答案作为也支持的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)

一些阅读:

可以对multi-line或长单行字符串中的变量使用Python 3.6's f-strings。可以使用\n手动指定换行符。

多行字符串中的变量

string1 = "go"
string2 = "now"
string3 = "great"

multiline_string = (f"I will {string1} there\n"
                    f"I will go {string2}.\n"
                    f"{string3}.")

print(multiline_string)

I will go there
I will go now
great

长单行字符串中的变量

string1 = "go"
string2 = "now"
string3 = "great"

singleline_string = (f"I will {string1} there. "
                     f"I will go {string2}. "
                     f"{string3}.")

print(singleline_string)

I will go there. I will go now. great.


或者,也可以创建带有三个引号的多行f-string。

multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""

相关问题 更多 >