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.

long_string = "This is a very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong string."
print(long_string)
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).

long_string = "This is a very" + "loooooooooooooooooooooooooooooooooooong string."
print(long_string)
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.

long_string = "This is a very looooooooooooooooooooooooooooooooooooong string."
print(long_string)
This is a very looooooooooooooooooooooooooooooooooooong string.

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

len("This is a very looooooooooooooooooooooooooooooooooooong string.")
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.

long_string = "This is a very looooooooooooooooooooooooooooooooooong string."
print(long_string)
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.

long_string = """This is a very
    loooooooooooooooooooooooooooooooooooooong string.
    """
print(long_string)
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.

import inspect
s = """
    if [[ -f ... ]]; then
        echo
    fi
    """
print(inspect.cleandoc(s))
if [[ -f ... ]]; then
    echo
fi
import textwrap
s = """\
    if [[ -f ... ]]; then
        echo
    fi
    """
print(textwrap.dedent(s))
if [[ -f ... ]]; then
    echo
fi