140

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

string1 = go
string2 = now
string3 = great

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

我正在寻找是否有类似于$Perl 的东西来指示 Python 语法中的变量。

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

4

7 回答 7

207

常用的方式是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'

最接近您所要求的内容(就语法而言)是模板字符串。例如:

>>> 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()功能更常见,因为它很容易获得并且不需要导入行。

于 2012-04-11T19:32:23.383 回答
60

注意:在 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)

一些阅读:

于 2012-04-11T19:32:09.927 回答
47

您可以将Python 3.6 的 f 字符串用于多行或冗长的单行字符串中的变量。您可以使用 手动指定换行符\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)

我会去那里
我现在去
很棒

冗长的单行字符串中的变量

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

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

print(singleline_string)

我将会去那里。我要走了。伟大的。


或者,您也可以创建带有三引号的多行 f 字符串。

multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""
于 2017-10-30T20:15:35.760 回答
13

f-strings,也称为“格式化字符串文字”,是f开头有 a 的字符串文字;和花括号,其中包含将被其值替换的表达式。

f 字符串在运行时进行评估。

所以你的代码可以重写为:

string1="go"
string2="now"
string3="great"
print(f"""
I will {string1} there
I will go {string2}
{string3}
""")

这将评估为:

I will go there
I will go now
great

您可以在此处了解更多信息。

于 2020-06-28T08:39:22.677 回答
12

这就是你想要的:

>>> 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
于 2012-04-11T19:43:55.593 回答
8

可以将字典传递给format(),每个键名将成为每个关联值的变量。

dict = {'string1': 'go',
        'string2': 'now',
        'string3': 'great'}

multiline_string = '''I'm will {string1} there
I will go {string2}
{string3}'''.format(**dict)

print(multiline_string)


也可以将列表传递给format(),在这种情况下,每个值的索引号将用作变量。

list = ['go',
        'now',
        'great']

multiline_string = '''I'm will {0} there
I will go {1}
{2}'''.format(*list)

print(multiline_string)


上述两种解决方案都将输出相同的结果:

我会去那里
我现在去
很棒

于 2015-09-18T07:52:56.820 回答
5

如果有人从 python-graphql 客户端来到这里寻找将对象作为变量传递的解决方案,这就是我使用的:

query = """
{{
  pairs(block: {block} first: 200, orderBy: trackedReserveETH, orderDirection: desc) {{
    id
    txCount
    reserveUSD
    trackedReserveETH
    volumeUSD
  }}
}}
""".format(block=''.join(['{number: ', str(block), '}']))

 query = gql(query)

确保像我一样转义所有花括号:“{{”,“}}”

于 2020-06-28T04:28:54.997 回答