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()功能更常见,因为它很容易获得,而且不需要输入线.
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)
一些阅读:
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)
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)
确保像我一样转义所有花括号:“{{”,“}}”
那就是你想要的:
>>> 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)
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)
您可以在此处了解更多信息。
可以传递字典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)
以上两种解决方案都会输出相同的:
我会去那里,
我现在会
很好
| 归档时间: |
|
| 查看次数: |
90177 次 |
| 最近记录: |