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
$string3
"""
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?
I think that the answer above forgot the {}:
The common way is the
format()
function:It works fine with a multi-line format string:
You can also pass a dictionary with variables:
The closest thing to what you asked (in terms of syntax) are template strings. For example:
I should add though that the
format()
function is more common because it's readily available and it does not require an import line.A dictionary can be passed to
format()
, each key name will become a variable for each associated value.Also a list can be passed to
format()
, the index number of each value will be used as variables in this case.Both solutions above will output the same:
NOTE: The recommended way to do string formatting in Python is to use
format()
, as outlined in the accepted answer. I'm preserving this answer as an example of the C-style syntax that's also supported.Some reading:
That what you want:
You can use Python 3.6's f-strings for variables inside multi-line or lengthy single-line strings. You can manually specify newline characters using
\n
.Variables in a multi-line string
Variables in a lengthy single-line string
Alternatively, you can also create a multiline f-string with triple quotes.