Concatenate strings in python in multiline
There are several ways. A simple solution is to add parenthesis:
strz = ("This is a line" +
str1 +
"This is line 2" +
str2 +
"This is line 3")
If you want each "line" on a separate line you can add newline characters:
strz = ("This is a line\n" +
str1 + "\n" +
"This is line 2\n" +
str2 + "\n" +
"This is line 3\n")
Solutions for Python 3 using Formatted Strings
As of Python 3.6 you can use so called "formatted strings" (or "f strings") to easily insert variables into your strings. Just add an f
in front of the string and write the variable inside curly braces ({}
) like so:
>>> name = "John Doe"
>>> f"Hello {name}"
'Hello John Doe'
To split a long string to multiple lines surround the parts with parentheses (()
) or use a multi-line string (a string surrounded by three quotes """
or '''
instead of one).
1. Solution: Parentheses
With parentheses around your strings you can even concatenate them without the need of a +
sign in between:
a_str = (f"This is a line \n{str1}\n"
f"This is line 2 \n{str2}\n"
"This is line 3") # no variable in this line, so no leading f
Good to know: If there is no variable in a line, there is no need for a leading f
for that line.
Good to know: You could archive the same result with backslashes (\
) at the end of each line instead of surrounding parentheses but accordingly to PEP8 you should prefer parentheses for line continuation:
Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
2. Solution: Multi-Line String
In multi-line strings you don't need to explicitly insert \n
, Python takes care of that for you:
a_str = f"""This is a line
{str1}
This is line 2
{str2}
This is line 3"""
Good to know: Just make sure you align your code correctly otherwise you will have leading white space in front each line.
By the way: you shouldn't call your variable str
because that's the name of the datatype itself.
Sources for formatted strings:
- What's new in Python 3.6
- PEP498