Concatenate strings in python in multiline

PythonStringConcatenation

Python Problem Overview


I have some strings to be concatenated and the resultant string will be quite long. I also have some variables to be concatenated.

How can I combine both strings and variables so the result would be a multiline string?

The following code throws error.

str = "This is a line" +
       str1 +
       "This is line 2" +
       str2 +
       "This is line 3" ;

I have tried this too

str = "This is a line" \
      str1 \
      "This is line 2" \
      str2 \
      "This is line 3" ;

Please suggest a way to do this.

Python Solutions


Solution 1 - Python

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")

Solution 2 - Python

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:

Solution 3 - Python

Python isn't php and you have no need to put $ before a variable name.

a_str = """This is a line
       {str1}
       This is line 2
       {str2}
       This is line 3""".format(str1="blabla", str2="blablabla2")

Solution 4 - Python

I would add everything I need to concatenate to a list and then join it on a line break.

my_str = '\n'.join(['string1', variable1, 'string2', variable2])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3290349View Question on Stackoverflow
Solution 1 - PythonBryan OakleyView Answer on Stackoverflow
Solution 2 - PythonwinklerrrView Answer on Stackoverflow
Solution 3 - PythonDiogo MartinsView Answer on Stackoverflow
Solution 4 - PythonDušan MaďarView Answer on Stackoverflow