Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Work with Long Strings in Python

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.

In [1]:
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).

In [9]:
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.

In [15]:
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.

In [14]:
len("This is a very " "looooooooooooooooooooooooooooooooooooong string.")
Out[14]:
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.

In [17]:
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.

In [2]:
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.

In [3]:
import inspect
In [3]:
s = """
    if [[ -f ... ]]; then
        echo
    fi
    """
In [6]:
print(inspect.cleandoc(s))
if [[ -f ... ]]; then
    echo
fi
In [1]:
import textwrap
In [7]:
s = """\
    if [[ -f ... ]]; then
        echo
    fi
    """
In [8]:
print(textwrap.dedent(s))
if [[ -f ... ]]; then
    echo
fi

In [ ]:
 

Comments