The string I am writing is very long. To make it easier to read, I would like to wrap the text onto multiple lines. How is this done?
Python allows you to split a long string in your source code into multiple substrings. Syntactically, adjacent string literals are simply concatenated; so "foo" "bar" is exactly equivalent to "foobar".
lorem_ipsum = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, "
"sed do eiusmod tempor incididunt ut labore et "
"dolore magna aliqua. Ut enim ad minim veniam, quis "
"nostrud exercitation ullamco laboris nisi ut aliquip "
"ex ea commodo consequat. Duis aute irure dolor in "
"reprehenderit in voluptate velit esse cillum dolore "
"eu fugiat nulla pariatur. Excepteur sint occaecat "
"cupidatat non proident, sunt in culpa qui officia "
"deserunt mollit anim id est laborum."
)
In IDLE, when you enter this, you'll see the ... prompt instead of the >>> prompt while you're in between the parentheses.
The parentheses aren't strictly necessary, either; you can backslash-escape newlines instead.
lorem_ipsum = \
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, " \
"sed do eiusmod tempor incididunt ut labore et " \
...
If your string contains newlines, a triple-quoted string is the obvious choice.
lorem_ipsum = """\
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore
eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum."""
Here, the backslash after the opening """ escapes the newline so that it's not part of the string; the first characters are "Lorem ipsum". The newlines after "elit," "et" etc are part of the string, though.
To wrap strings you output, maybe look at the textwrap module in the standard library. If you like, you can obviously also use that to keep strings in your source code formatted in a manner which is convenient while editing - one common trick is to have indented multi-line strings in your source for visual consistency, but remove the indentation when you actually use the string:
from textwrap import dedent
if condition:
while state:
for elt in elements:
paragraph = f"""\
Convenient indented
string with {condition}
and {state} and {elt}""".dedent()
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