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

evo*_*ion 78 python string variables multiline

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

string1 = go
string2 = now
string3 = great

"""
I will $string1 there
I will go $string2
$string3
"""
Run Code Online (Sandbox Code Playgroud)

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

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

Sim*_*ser 126

常见的方法是format()功能:

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
Run Code Online (Sandbox Code Playgroud)

它适用于多行格式字符串:

>>> 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.
Run Code Online (Sandbox Code Playgroud)

您还可以传递包含变量的字典:

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
Run Code Online (Sandbox Code Playgroud)

与您提出的问题(就语法而言)最接近的是模板字符串.例如:

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

我应该补充说,这个format()功能更常见,因为它很容易获得,而且不需要输入线.

  • 可以使用`vars()`或`locals()`作为相关词典 (2认同)
  • @isbadawi显式优于隐式.最好只传入你需要的变量.如果你不知道你需要哪个,因为字符串是由用户提供的,"变量"应该是"dict"中的项目. (2认同)
  • 如果使用花括号,它们需要像 `{{this}}` 一样被转义。 (2认同)

Dav*_*ain 45

注意:在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)
Run Code Online (Sandbox Code Playgroud)

一些阅读:

  • "*你可能已经用一点谷歌搜索来回答这个问题*"暗示我们在谷歌搜索之后没有找到这篇帖子...... (3认同)
  • 这不是真的相同,因为OP需要命名参数,而不是位置参数. (2认同)
  • 它仍然是一个很好的解决方案,对于多行插值来说它更直接。您不必导入任何内容,它使用常规的 Python 插值。 (2认同)

Ste*_*ica 20

您可以将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)
Run Code Online (Sandbox Code Playgroud)

我会去那里,
我现在会
很好

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

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

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

print(singleline_string)
Run Code Online (Sandbox Code Playgroud)

我将会去那里.我要走了.大.


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

multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""
Run Code Online (Sandbox Code Playgroud)

  • 三重引用是*非常*优选的。您应该首先提交该表格。 (18认同)

Rad*_*anu 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)
Run Code Online (Sandbox Code Playgroud)

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


Hav*_*vok 8

那就是你想要的:

>>> 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
Run Code Online (Sandbox Code Playgroud)


Ans*_*ngh 7

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

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

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

string1="go"
string2="now"
string3="great"
print(f"""
I will {string1} there
I will go {string2}
{string3}
""")
Run Code Online (Sandbox Code Playgroud)

这将评估为:

I will go there
I will go now
great
Run Code Online (Sandbox Code Playgroud)

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


jes*_*unk 6

可以传递字典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)
Run Code Online (Sandbox Code Playgroud)


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

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

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

print(multiline_string)
Run Code Online (Sandbox Code Playgroud)


以上两种解决方案都会输出相同的:

我会去那里,
我现在会
很好