Use a backslash ( \ ) as a line continuation character In Python, a backslash ( \ ) is a line continuation character. If a backslash is placed at the end of a line, it is considered that the line is continued on the next line.
Multiline Python f Strings You can create a multiline Python f string by enclosing multiple f strings in curly brackets. In our code, we declared three variables — name, email, and age — which store information about our user. Then, we created a multiline string which is formatted using those variables.
According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.
PythonServer Side ProgrammingProgramming. Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example − total = item_one + \ item_two + \ item_three.
Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:
print("Why, hello there wonderful "
"stackoverflow people!")
Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:
my_string = "The quick brown dog " \
"jumped over the lazy fox"
Another possibility is to use the textwrap module. This also avoids the problem of "string just sitting in the middle of nowhere" as mentioned in the question.
import textwrap
mystr = """\
Why, hello there
wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))
This is a pretty clean way to do it:
myStr = ("firstPartOfMyString"+
"secondPartOfMyString"+
"thirdPartOfMyString")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With