Jak utworzyć wielowierszowy ciąg Pythona ze zmiennymi inline?
Szukam czystego sposobu użycia zmiennych w wielowierszowym łańcuchu Pythona. Powiedzmy, że chciałem zrobić co następuje:
string1 = go
string2 = now
string3 = great
"""
I will $string1 there
I will go $string2
$string3
"""
Szukam czegoś podobnego do $
w Perlu, co wskazywałoby zmienną w składni Pythona.
Jeśli nie - jaki jest najczystszy sposób tworzenia ciągu wielowierszowego ze zmiennymi?
6 answers
Wspólną drogą jest format()
Funkcja:
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
Działa dobrze z ciągiem wielowierszowym:
>>> 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.
Możesz również przekazać słownik ze zmiennymi:
>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
Najbliższą rzeczą do tego, o co prosiłeś (pod względem składni) są ciągi szablonów. Na przykład:
>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
Powinienem jednak dodać, że funkcja format()
jest bardziej powszechna, ponieważ jest łatwo dostępna i nie wymaga linii importu.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-01 02:45:18
Uwaga : zalecanym sposobem formatowania łańcuchów w Pythonie jest użycie format()
, jak opisano w zaakceptowanej odpowiedzi. Zachowuję tę odpowiedź jako przykład składni w stylu C, która jest również obsługiwana.
# 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)
Niektóre lektury:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-31 02:13:21
Możesz użyć ciągów f Pythona 3.6 dla zmiennych wewnątrz wielowierszowych lub długich ciągów jednowierszowych. Można ręcznie określić znaki nowej linii za pomocą \n
.
Zmienne w ciągu wielowierszowym
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)
Pójdę tam
I will go now
great
Zmienne w długim ciągu jednoliniowym
string1 = "go"
string2 = "now"
string3 = "great"
singleline_string = (f"I will {string1} there. "
f"I will go {string2}. "
f"{string3}.")
print(singleline_string)
Pójdę tam. Pójdę już. świetnie.
Alternatywnie, można również utworzyć wieloliniowy ciąg f z potrójnymi cudzysłowami.
multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-20 19:42:18
Słownik można przekazać do format()
, każda nazwa klucza stanie się zmienną dla każdej powiązanej wartości.
dict = {'string1': 'go',
'string2': 'now',
'string3': 'great'}
multiline_string = '''I'm will {string1} there
I will go {string2}
{string3}'''.format(**dict)
print(multiline_string)
Również listę można przekazać do format()
, Numer indeksu każdej wartości będzie w tym przypadku używany jako zmienne.
list = ['go',
'now',
'great']
multiline_string = '''I'm will {0} there
I will go {1}
{2}'''.format(*list)
print(multiline_string)
Oba powyższe rozwiązania dają taki sam wynik:
I ' m will go there
I will go now
great
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-30 21:36:31
That what you want:
>>> 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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-31 02:12:37
Myślę, że odpowiedź powyżej zapomniała {}:
from string import Template
t = Template("This is an ${example} with ${vars}")
t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-11 20:43:58