如何创建带有内联变量的多行Python字符串?

问题描述 投票:0回答:10

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

string1 = go
string2 = now
string3 = great

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

我想看看 Perl 中是否有类似于

$
的东西来指示 Python 语法中的变量。

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

python string variables multiline
10个回答
262
投票

常用的方式是

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


81
投票

您可以将 Python 3.6 的 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)

我会去那里
我现在就去
太棒了

长单行字符串中的变量

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}."""

72
投票

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

一些阅读:


31
投票

f-strings,也称为“格式化字符串文字”,是开头有

f
的字符串文字;和花括号包含将被其值替换的表达式。

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

您可以在这里了解更多信息。


14
投票
这就是你想要的:

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

13
投票
如果有人从 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)
确保像我一样转义所有花括号:“{{”,“}}”


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)

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

我会去那里

我现在就去
太棒了


2
投票
print (f" \ What you want to write {var_one} \n \ What you want to write {var_two} \n \ What you want to write {var_three} \n \ Et cetera {var_four}")
这对我有用。也许它对某人有帮助,干杯


2
投票
最简单的方法是使用 f 字符串多行。

string1 = "go" string2 = "now" string3 = "great" s = f""" I will {string1} there I will go {string2} {string3} """ print(s)
这将会回归。

I will go there I will go now great
希望这有帮助。


0
投票
这里是一个在 @dataclass 中将字符串分成多行以与 QT 样式表一起使用的示例。请注意包含缩进和斜线。

@dataclass class button_a: i: str = "QPushButton:hover {background: qradialgradient(cx:0, cy:0, radius:1,fx:0.5,fy:0.5,stop:0 white, stop:1 green);"\ "color:qradialgradient(cx:0, cy:0, radius:1,fx:0.5,fy:0.5,stop:0 yellow, stop:1 brown);"\ "border-color: purple;}"


    

© www.soinside.com 2019 - 2024. All rights reserved.