note.nkmk.me

Write a long string into multiple lines of code in Python

Posted: 2019-05-29 / Tags: Python, String

When using PEP8 code checkers such as flake8 in Python, an error of E501 line too long occurs when one line exceeds 80 characters.

This article describes how to write a long string that does not contain a newline into multiple lines of code.

  • Use a backslash (\)
  • Use parentheses

See the following article for various operation related to strings including line breaks.

If you want to wrap or truncate long strings, the textwrap module is useful. See the following article.

If the number of characters in a line becomes too long due to method chaining, the line can be broken in the same way.

Sponsored Link

Use a backslash (\)

In Python, a backslash (\) is a continuation character, and if it is placed at the end of a line, it is considered that the line is continued, ignoring subsequent newlines.

n = 1 + 2 \
    + 3

print(n)
# 6

Also, if multiple string literals are written sequentially, they will be concatenated into one string as follows:

s = 'aaa' 'bbb'

print(s)
# aaabbb

Combining these two properties, we can write a long string into multiple lines of code, as follows:

s = 'https://ja.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'

print(s)
# https://ja.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

Only string literals (string surrounded by '' or " ") are concatenated if they are written consecutively. Note that in the case of variables, errors will occur.

s_var = 'xxx'

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

Use the + operator to concatenate variables, or variables and string literals.

s = 'aaa' + s_var + 'bbb'

print(s)
# aaaxxxbbb

You need the + operator to concatenate variables, even if they are separated by a backslash (\).

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

print(s)
# aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaxxxbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

See the following article for details of string concatenation.

Use parentheses

In Python, you can freely break the line in parentheses ((), {}, []). Using this rule, you can use parentheses instead of backslashes.

Since {} is used for set and [] is used for list, use () for such purpose.

It can be written as follows.

s = ('https://ja.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')

print(s)
# https://ja.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

If variables are included, you need the + operator.

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

print(s)
# aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaxxxbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Sponsored Link
Share

Related Categories

Related Articles