¿Cómo puedo crear una cadena de Python multilínea con variables en línea?
Estoy buscando una forma limpia de usar variables dentro de una cadena de Python multilínea. Digamos que quería hacer lo siguiente:
string1 = go
string2 = now
string3 = great
"""
I will $string1 there
I will go $string2
$string3
"""
Estoy buscando ver si hay algo similar a $
en Perl para indicar una variable en la sintaxis de Python.
Si no, ¿cuál es la forma más limpia de crear una cadena multilínea con variables?
6 answers
La forma común es la función format()
:
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
Funciona bien con una cadena de formato multilínea:
>>> 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.
También puede pasar un diccionario con variables:
>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
Lo más parecido a lo que has preguntado (en términos de sintaxis) son cadenas de plantillas. Por ejemplo:
>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
Debo agregar que la función format()
es más común porque está fácilmente disponible y no requiere una línea de importación.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-01 02:45:18
NOTA: La forma recomendada de formatear cadenas en Python es usar format()
, como se describe en la respuesta aceptada. Estoy preservando esta respuesta como un ejemplo de la sintaxis de estilo C que también es compatible.
# 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)
Alguna lectura:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-31 02:13:21
Puede usar las cadenas f de Python 3.6 para variables dentro de cadenas multilíneas o largas cadenas de una sola línea. Puede especificar manualmente caracteres de nueva línea usando \n
.
Variables en una cadena multilínea
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)
Iré allí{[14]]} Me iré ahora
gran
Variables en una cadena larga de una sola línea
string1 = "go"
string2 = "now"
string3 = "great"
singleline_string = (f"I will {string1} there. "
f"I will go {string2}. "
f"{string3}.")
print(singleline_string)
Iré allí. Me iré ahora. gran.
Alternativamente, también puede crear un f-string multilínea con comillas triples.
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-20 19:42:18
Se puede pasar un diccionario a format()
, cada nombre de clave se convertirá en una variable para cada valor asociado.
dict = {'string1': 'go',
'string2': 'now',
'string3': 'great'}
multiline_string = '''I'm will {string1} there
I will go {string2}
{string3}'''.format(**dict)
print(multiline_string)
También se puede pasar una lista a format()
, el número índice de cada valor se utilizará como variables en este caso.
list = ['go',
'now',
'great']
multiline_string = '''I'm will {0} there
I will go {1}
{2}'''.format(*list)
print(multiline_string)
Ambas soluciones anteriores generarán lo mismo:
Voy a ir allí
Me iré ahora
gran
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-30 21:36:31
Que lo que quieres:
>>> 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-31 02:12:37
Creo que la respuesta anterior olvidó el {}:
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-11 20:43:58