PEP8
Python
E501
long string
code style

How to write very long string that conforms with PEP8 and prevent E501

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

PEP 8 recommends a maximum line length of 79 characters (or 99/120 for many projects). The E501 lint error triggers when a line exceeds this limit. Long strings — URLs, SQL queries, log messages — frequently exceed this threshold. Python provides several ways to split long strings across multiple lines without changing their content: implicit string concatenation, parenthesized strings, backslash continuation, textwrap.dedent, and f-string splitting. The right approach depends on whether the string contains newlines and how readable the result needs to be.

Adjacent string literals are automatically concatenated by the Python compiler. No + operator is needed.

python
1# Adjacent strings inside parentheses are joined at compile time
2message = (
3    "This is a very long message that would exceed "
4    "the PEP 8 line length limit if written on a "
5    "single line."
6)
7print(message)
8# "This is a very long message that would exceed the PEP 8 line length limit if written on a single line."
9
10# No runtime overhead — the compiler joins them into one string

Parenthesized Strings with f-strings

python
1name = "Alice"
2count = 42
3
4# Split f-strings across multiple lines
5message = (
6    f"Hello {name}, you have {count} new "
7    f"notifications waiting in your inbox."
8)
9
10# Mix f-strings and regular strings
11url = (
12    f"https://api.example.com/v2/users/{name}"
13    f"/notifications?limit={count}"
14    "&sort=date&order=desc"
15)

Backslash Continuation

python
1# Backslash at end of line continues to the next
2message = "This is a very long message that would " \
3          "exceed the line length limit."
4
5# Works but parentheses are preferred — backslash is fragile
6# (a space after \ causes a syntax error)

PEP 8 prefers parentheses over backslash continuation.

Long URLs and Paths

python
1# URLs should not be split (they become unusable if broken)
2# PEP 8 allows exceptions for URLs — put them on one line or in a variable
3
4# Option 1: Assign to a variable (line may still be long)
5API_ENDPOINT = "https://api.example.com/v2/users/search?query=active&limit=100&offset=0"  # noqa: E501
6
7# Option 2: Build the URL
8base = "https://api.example.com/v2/users/search"
9params = "?query=active&limit=100&offset=0"
10url = base + params

Multi-Line SQL Queries

python
1# Triple-quoted strings preserve newlines and whitespace
2query = """
3    SELECT u.name, u.email, o.total
4    FROM users u
5    JOIN orders o ON u.id = o.user_id
6    WHERE o.created_at > %s
7    ORDER BY o.total DESC
8    LIMIT 100
9"""
10
11# textwrap.dedent removes common leading whitespace
12import textwrap
13
14query = textwrap.dedent("""
15    SELECT u.name, u.email, o.total
16    FROM users u
17    JOIN orders o ON u.id = o.user_id
18    WHERE o.created_at > %s
19""").strip()

Long Function Arguments

python
1# Split long function calls across multiple lines
2result = some_function(
3    first_argument="hello",
4    second_argument="world",
5    third_argument=42,
6    fourth_argument=True,
7)
8
9# Long string as an argument
10logger.warning(
11    "Connection to %s failed after %d retries "
12    "with error: %s",
13    hostname, max_retries, error_message,
14)

Suppressing E501 for Specific Lines

python
1# Add noqa comment to suppress E501 on a specific line
2LONG_CONSTANT = "https://very-long-domain.example.com/api/v2/endpoint?param=value"  # noqa: E501
3
4# Configure the max line length in your linter config
5# pyproject.toml
6# [tool.flake8]
7# max-line-length = 120
8
9# .flake8
10# [flake8]
11# max-line-length = 120
12
13# ruff.toml
14# line-length = 120

Common Pitfalls

  • Accidentally inserting spaces or newlines: Implicit concatenation joins strings exactly as written. "hello " "world" produces "hello world" (with a space), but "hello" "world" produces "helloworld" (no space). Always check where spaces go when splitting.
  • Using + instead of implicit concatenation: "a" + "b" creates a runtime concatenation, while "a" "b" is compiled into a single string "ab". The + version has (tiny) runtime overhead and is less idiomatic for splitting long literals.
  • Triple-quoted strings including unwanted indentation: """ strings preserve all whitespace including indentation in your source code. Use textwrap.dedent() to strip common leading whitespace, or use parenthesized implicit concatenation for strings that should not contain newlines.
  • Breaking URLs or file paths: Splitting a URL or file path across lines changes the string content (adds no separator by default). If you forget a space or add an unwanted one, the URL becomes invalid. Keep URLs on one line with # noqa: E501 or build them from parts.
  • Space after backslash continuation: A backslash followed by a space and then a newline (\ \n) is a syntax error, not a line continuation. This is invisible and hard to debug. Parenthesized strings do not have this problem, which is why PEP 8 prefers them.

Summary

  • Use parenthesized implicit concatenation for long strings: ("part one " "part two")
  • Use triple-quoted strings with textwrap.dedent() for multi-line content like SQL
  • PEP 8 prefers parentheses over backslash continuation
  • Use # noqa: E501 for URLs and other strings that should not be split
  • Configure your linter's max-line-length to match your project's convention (79, 99, or 120)

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions