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
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
.
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)
I will go there
I will go now
great
string1 = "go"
string2 = "now"
string3 = "great"
singleline_string = (f"I will {string1} there. "
f"I 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 = f"""I will {string1} there.
I will go {string2}.
{string3}."""