Writing long strings of text on multiple lines in Python

Money and Business

If you use a PEP8 compliant code checker such as flake8 in Python, you will get the following error when a line exceeds 80 characters.E501 line too longI will show you how to break a long string of more than 80 characters, such as a URL, into multiple lines of code.

  • Ignore line breaks with backslashes (\)
  • Line breaks can be freely enclosed in parentheses

The textwrap module is also useful if you want to output and display long strings by wrapping or omitting them.
If you have a method chain that is longer than a single line of characters, rather than a long string, you can break the line in the code as well.

Ignore line breaks with backslashes (\)

In Python, the backslash (\) is a continuation character, and when placed at the end of a line, it ignores subsequent line breaks and assumes the line is continuing.

n = 1 + 2 \
    + 3

# 6

Also, when multiple string literals are written in succession, they are concatenated to form a single string as shown below.

s = 'aaa' 'bbb'

# aaabbb

Combining the two, a long string can be written in multiple lines of code, as shown below.

s = 'https://wikipedia.org/wiki/'\

# https://wikipedia.org/wiki/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0%E8%A8%80%E8%AA%9E

Note that only string literals (enclosed in ' or “”) can be concatenated, and variables containing strings will result in an error.

s_var = 'xxx'

# s = 'aaa' s_var 'bbb'
# SyntaxError: invalid syntax

To concatenate variables to each other or variables to string literals, use the + operator.

s = 'aaa' + s_var + 'bbb'

# aaaxxxbbb

Even when separated by a backslash (\), the + operator is required to concatenate variables.

s = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\
    + s_var\
    + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'

# aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaxxxbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

Line breaks can be freely enclosed in parentheses

In Python, you can freely break lines within the following parentheses. You can use this rule to enclose long strings of text in parentheses.

  • ()
  • {}
  • []

Note that the following parentheses have a meaning.

  • {} = set
  • [] = list

Therefore, when writing a long string on multiple lines, use round brackets ().
Again, using the fact that multiple strings can be concatenated together to form a single string, we can write the following.

s = ('https://wikipedia.org/wiki/'

# https://wikipedia.org/wiki/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0%E8%A8%80%E8%AA%9E

As in the example with the backslash, the + operator is required when variables are included.

s = ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
     + s_var
     + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')

# aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaxxxbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Copied title and URL