How do I create a multiline Python string with inline variables?


I am looking for a clean way to use variables within a multiline Python string. Say I wanted to do the following:

string1 = go
string2 = now
string3 = great

I will $string1 there
I will go $string2

I"m looking to see if there is something similar to $ in Perl to indicate a variable in the Python syntax.

If not - what is the cleanest way to create a multiline string with variables?

Answer rating: 192

The common way is the format() function:

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
"This is an example with variables"

It works fine with a multi-line format string:

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

You can also pass a dictionary with variables:

>>> d = { "vars": "variables", "example": "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
"This is an example with variables"

The closest thing to what you asked (in terms of syntax) are template strings. For example:

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

I should add though that the format() function is more common because it"s readily available and it does not require an import line.

Get Solution for free from DataCamp guru