Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 660
user3290349 Avatar asked Dec 15 '15 17:12

user3290349


People also ask

How do you join strings between lines in Python?

Solution: Parentheses 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.

How do you concatenate 3 strings in Python?

Concatenation means joining strings together end-to-end to create a new string. To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.


1 Answers

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") 
like image 162
Bryan Oakley Avatar answered Oct 06 '22 00:10

Bryan Oakley