Concatenate strings in python in multiline

user3290349 picture user3290349 · Dec 15, 2015 · Viewed 50.2k times · Source

I have some strings to be concatenate 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 multi line 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.

Answer

Bryan Oakley picture Bryan Oakley · Dec 15, 2015

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