Search code examples
pythonstringconcatenation

Concatenate strings in python in multiline


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.


Solution

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