How do I create a multiline Python string with inline variables?
How do I create a multiline Python string with inline variables?
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 its readily available and it does not require an import line.
NOTE: The recommended way to do string formatting in Python is to use format()
, as outlined in the accepted answer. Im preserving this answer as an example of the C-style syntax thats also supported.
# 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)
Some reading:
How do I create a multiline Python string with inline variables?
You can use Python 3.6s 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
string1 = go
string2 = now
string3 = great
multiline_string = (fI will {string1} theren
fI will go {string2}.n
f{string3}.)
print(multiline_string)
I will go there
I will go now
great
Variables in a lengthy single-line string
string1 = go
string2 = now
string3 = great
singleline_string = (fI will {string1} there.
fI will go {string2}.
f{string3}.)
print(singleline_string)
I will go there. I will go now. great.
Alternatively, you can also create a multiline f-string with triple quotes.
multiline_string = fI will {string1} there.
I will go {string2}.
{string3}.