This article discusses different ways to write long strings in Python.
Long String in One Line¶
A long string can be put on the the same line, which is ugly of course.
long_string = "This is a very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong string."
print(long_string)
Concatenate Multiple Strings Using +
¶
Use +
to concatenate multiple string,
which is is visually good but not recommended (due to simpler alternatives).
long_string = "This is a very" + "loooooooooooooooooooooooooooooooooooong string."
print(long_string)
Parentheses¶
Parentheses can be used to break a long string into multiple lines and avoid the side effect of white spaces at the same time.
long_string = "This is a very " "looooooooooooooooooooooooooooooooooooong string."
print(long_string)
This is especially convenient if the long string is passed directly to a method.
len("This is a very " "looooooooooooooooooooooooooooooooooooong string.")
Line Continuation \
¶
The line continuation symbol \
can be used to break a string into multiple lines.
This is another good alternative if you do not like the parentheses way.
long_string = "This is a very " "looooooooooooooooooooooooooooooooooong string."
print(long_string)
Triple Quotes¶
Triple double/single quotes is a very convenient way to write a large chunk of string in Python. Howeve, whites spaces are kept literally in a triple-qutoe string, which might or might not be what you want.
long_string = """This is a very
loooooooooooooooooooooooooooooooooooooong string.
"""
print(long_string)
Fortunately, there are a few functions in Python which can easily remove leading whites spaces in each line of a tripple quotes string.
import inspect
s = """
if [[ -f ... ]]; then
echo
fi
"""
print(inspect.cleandoc(s))
import textwrap
s = """\
if [[ -f ... ]]; then
echo
fi
"""
print(textwrap.dedent(s))