Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

This is a very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong string.

Concatenate Multiple Strings Using +

Use + to concatenate multiple string, which is is visually good but not recommended (due to simpler alternatives).

This is a veryloooooooooooooooooooooooooooooooooooong 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.

This is a very looooooooooooooooooooooooooooooooooooong string.

This is especially convenient if the long string is passed directly to a method.

63

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.

This is a very looooooooooooooooooooooooooooooooooong 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.

This is a very
    loooooooooooooooooooooooooooooooooooooong string.
    

Fortunately, there are a few functions in Python which can easily remove leading whites spaces in each line of a tripple quotes string.

if [[ -f ... ]]; then
    echo
fi
if [[ -f ... ]]; then
    echo
fi