python
line-wrapping
programming
duplicate-question
code-formatting

Wrap long lines in Python

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

Wrapping long lines in Python can mean two different things: formatting Python source code, or wrapping text that a Python program prints at runtime. Those are separate problems and should be handled differently. For source code, use Python syntax and a formatter. For text output, use the textwrap module.

Wrap Source Code with Implicit Continuation

For Python source, the safest approach is implicit continuation inside parentheses, brackets, or braces. This is clearer and more robust than backslash continuation.

python
1def build_query(user_id, status, start_date):
2    return (
3        "SELECT id, email, created_at "
4        "FROM users "
5        "WHERE user_id = %s "
6        "AND status = %s "
7        "AND created_at >= %s "
8        "ORDER BY created_at DESC"
9    )

This works because adjacent string literals are concatenated automatically inside parentheses. The same style is good for long arithmetic expressions, function calls, and container literals.

python
1result = send_email(
2    to_address="[email protected]",
3    subject="Daily report",
4    body=report_body,
5    retry_count=3,
6    timeout_seconds=10,
7)

The main goal is not squeezing code under a line limit at any cost. The goal is making the wrapped structure easy to scan.

Avoid Backslashes Unless You Really Need Them

Python allows line continuation with a backslash, but it is easy to break during editing.

python
total = subtotal + \
    tax_amount + \
    shipping_cost

This is valid, but it is fragile. A stray space or comment can break the statement in ways that are annoying to diagnose. Prefer this form instead:

python
1total = (
2    subtotal
3    + tax_amount
4    + shipping_cost
5)

Parenthesized continuation is the style used by most modern Python formatters for good reason.

Let a Formatter Enforce the Rule

For team code, automated formatting is better than hand-wrapping every file. black is the most common choice.

bash
black .
black --check .

A minimal pyproject.toml might look like this:

toml
[tool.black]
line-length = 100

Once the formatter is part of the workflow, line wrapping becomes consistent across editors, contributors, and CI runs. That removes style churn from code review.

Use textwrap for Runtime Output

If the problem is wrapping paragraphs, help text, or email bodies at runtime, use the standard library.

python
1import textwrap
2
3message = (
4    "The backup finished successfully, but two files were skipped "
5    "because their source paths no longer existed."
6)
7
8print(textwrap.fill(message, width=50))

textwrap.fill returns one wrapped string. textwrap.wrap returns a list of lines. Both are useful depending on whether you need to print or further process the result.

Preserve Paragraph Structure Intentionally

For multi-paragraph text, wrap each paragraph separately instead of flattening everything.

python
1import textwrap
2
3
4def wrap_paragraphs(text, width=72):
5    paragraphs = text.strip().split("\n\n")
6    wrapped = [textwrap.fill(p, width=width) for p in paragraphs]
7    return "\n\n".join(wrapped)

That keeps blank lines meaningful and avoids output that looks like one giant block.

Adapt Width for CLI Programs

Hard-coding a width can work for reports, but CLI tools often benefit from using the current terminal size.

python
1import shutil
2import textwrap
3
4columns = shutil.get_terminal_size(fallback=(80, 24)).columns
5width = max(40, columns - 2)
6
7text = "This command-line output adjusts to the terminal width for easier reading."
8print(textwrap.fill(text, width=width))

This makes the output more usable across small terminals, large terminals, and redirected execution environments.

Common Pitfalls

  • Treating source-code wrapping and runtime text wrapping as the same problem.
  • Using backslash continuation where parentheses would be clearer and safer.
  • Hand-formatting files inconsistently instead of letting a formatter enforce line length.
  • Wrapping machine-readable formats such as JSON or CSV just for visual appearance.
  • Losing paragraph boundaries by wrapping large text blobs without structure.

Summary

  • For Python source, prefer implicit continuation inside parentheses, brackets, or braces.
  • Avoid backslashes unless there is a specific reason to use them.
  • Use a formatter such as black to keep wrapping consistent across a team.
  • Use textwrap for human-facing text generated at runtime.
  • Keep code formatting and text formatting as separate concerns.

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

All Rights Reserved.