How to Split a Long String into Multiple Lines in Python

To split a long string into multiple lines in Python, use textwrap.wrap(text, width), which returns a list of lines broken at spaces, or textwrap.fill() for one string with line breaks. If the text already has newlines, splitlines() splits on them:

import textwrap
lines = textwrap.wrap(text, width=40)

My sample text is a short store notice, and the outputs come from Python 3.12.5. Nothing to install: textwrap ships with Python.

You’ll wrap text to a width, use indents and line limits, split text that has its own line breaks, cut fixed-size pieces, and write long strings across several lines in your code.

Wrap a long string at a fixed width with textwrap

wrap() won’t split a word in the middle unless it has to. The bars in this output show each line fits inside 40 characters:

text = ("Our Austin store opens at 7 AM on weekdays and 8 AM on weekends. Online orders over $50.00 "
        "ship free to every US state, and returns are accepted within 30 days of delivery.")
import textwrap

lines = textwrap.wrap(text, width=40)        # a list of lines, broken at spaces
for line in lines:
    print(f"|{line:<40}|")
print(len(lines), "lines")

print(textwrap.fill(text, width=60))         # one string with \n between lines

Output:

|Our Austin store opens at 7 AM on       |
|weekdays and 8 AM on weekends. Online   |
|orders over $50.00 ship free to every US|
|state, and returns are accepted within  |
|30 days of delivery.                    |
5 lines
Our Austin store opens at 7 AM on weekdays and 8 AM on
weekends. Online orders over $50.00 ship free to every US
state, and returns are accepted within 30 days of delivery.
Command Prompt output of Python textwrap.wrap splitting a long store notice into lines of at most 40 characters, then textwrap.fill at 60
wrap() gave a list of lines; fill() joined them with newlines at 60 characters.

Use wrap() when you need the lines separately, for example to draw them one by one, and fill() when you just want to print. Looping over the result works like iterating through a string in Python.

Indent, limit or shorten the wrapped lines

fill() and wrap() take options for bullet-style indents and for cutting text off after a number of lines. shorten() squeezes everything onto one line:

# text = the store notice from the first example
import textwrap

print(textwrap.fill(text, width=50, initial_indent="* ", subsequent_indent="  "))
print()
print(textwrap.fill(text, width=50, max_lines=2, placeholder=" [...]"))
print()
print(textwrap.shorten(text, width=60, placeholder="..."))
print(textwrap.wrap("SKU-TX-2026-ABCDEFGHIJKLMNOP", width=10))                  # long words get broken
print(textwrap.wrap("SKU-TX-2026-ABCDEFGHIJKLMNOP", width=10, break_long_words=False))
print(textwrap.wrap("SKU-TX-2026-ABCDEFGHIJKLMNOP", width=10, break_long_words=False, break_on_hyphens=False))

Output:

* Our Austin store opens at 7 AM on weekdays and 8
  AM on weekends. Online orders over $50.00 ship
  free to every US state, and returns are accepted
  within 30 days of delivery.

Our Austin store opens at 7 AM on weekdays and 8
AM on weekends. Online orders over $50.00 [...]

Our Austin store opens at 7 AM on weekdays and 8 AM on...
['SKU-TX-', '2026-', 'ABCDEFGHIJ', 'KLMNOP']
['SKU-', 'TX-2026-ABCDEFGHIJKLMNOP']
['SKU-TX-2026-ABCDEFGHIJKLMNOP']
Command Prompt output of Python textwrap with a hanging indent, max_lines with a placeholder, shorten, and break_long_words on a long SKU
A hanging indent, a two-line preview, a one-line summary, and three ways a long SKU gets split.

Look closely at the SKU: even with break_long_words=False, it’s still split after the hyphens. That’s break_on_hyphens, which is on by default. Turn both off to keep codes and URLs whole.

If you just need the start of a string, see getting the first N characters of a string.

Split a string that already has line breaks

When the text came from a file or an API, it already contains line breaks. splitlines() is usually the right tool, and it behaves differently from split("\n"):

report = "Austin,1250.50\r\nDenver,980.25\nTampa,1120.75\n"

print(report.split("\n"))          # keeps \r and adds an empty last item
print(report.splitlines())         # handles \r\n and \n, no empty last item
print(report.splitlines(keepends=True))
print("".split("\n"), "".splitlines())

Output:

['Austin,1250.50\r', 'Denver,980.25', 'Tampa,1120.75', '']
['Austin,1250.50', 'Denver,980.25', 'Tampa,1120.75']
['Austin,1250.50\r\n', 'Denver,980.25\n', 'Tampa,1120.75\n']
[''] []
Command Prompt output comparing Python split on newline with splitlines on text containing Windows and Unix line endings
split("\n") leaves \r behind and adds an empty last item; splitlines() doesn’t.

I use splitlines() for anything from Windows users, since \r\n endings are common there. For reading a file one line at a time instead, see reading a file line by line in Python.

Split a string into fixed-size pieces or by paragraph

Sometimes you need exact chunk sizes, like grouping a tracking number, and sometimes you need to wrap several paragraphs without merging them:

import textwrap

tracking = "1Z999AA10123456784US2026TX"
print([tracking[i:i + 6] for i in range(0, len(tracking), 6)])   # exact 6-character pieces

notes = """Store hours changed for the holidays. We close at 4 PM on Dec 24.

Gift cards never expire and can be used online or in any Texas location."""
paragraphs = notes.split("\n\n")                               # keep blank lines between paragraphs
print("\n\n".join(textwrap.fill(p, width=45) for p in paragraphs))

Output:

['1Z999A', 'A10123', '456784', 'US2026', 'TX']
Store hours changed for the holidays. We
close at 4 PM on Dec 24.

Gift cards never expire and can be used
online or in any Texas location.

Slicing ignores word boundaries, which is exactly what you want for codes. More slicing patterns are in splitting a string at every Nth character.

Write a long string across multiple lines in your code

A different meaning of “split a long string” is keeping a long literal readable in your source file. Triple quotes with textwrap.dedent(), or adjacent strings inside parentheses, both work:

import textwrap

def receipt():
    message = textwrap.dedent("""\
        Thanks for shopping with us!
          Order: A-2026-1005
          Total: $87.40
        See you again soon.""")
    return message

print(receipt())

long_sql = ("SELECT city, SUM(total) "
            "FROM orders "
            "WHERE state = 'TX' "
            "GROUP BY city")                     # adjacent literals are joined into one string
print(long_sql)

Output:

Thanks for shopping with us!
  Order: A-2026-1005
  Total: $87.40
See you again soon.
SELECT city, SUM(total) FROM orders WHERE state = 'TX' GROUP BY city
Command Prompt output of Python textwrap.dedent removing indentation from a triple-quoted receipt and adjacent string literals joined into one SQL query
dedent() removed the function’s indentation; the SQL pieces became one string with no line breaks.

The backslash after the opening """ stops an empty first line. For backslash continuation and other options, see continuing long strings on the next line.

Which method should you use?

GoalUse
Wrap text to a width (list of lines)textwrap.wrap(text, width)
Wrap text to a width (one string)textwrap.fill(text, width)
One-line previewtextwrap.shorten(text, width)
Split on existing line breakstext.splitlines()
Exact N-character pieces[s[i:i+n] for i in range(0, len(s), n)]
Long literal in source codeParentheses or textwrap.dedent()

Here are more guides for working with text in Python:

Frequently asked questions

How do I split a long string into multiple lines in Python?

Use textwrap.wrap(text, width=40) for a list of lines, or textwrap.fill(text, width=40) for one string with newlines.

Does textwrap break words in the middle?

Only when a single word is longer than the width, and it also breaks after hyphens. Pass break_long_words=False and break_on_hyphens=False to keep long words whole.

What’s the difference between splitlines() and split(“\n”)?

splitlines() handles \r\n and other line endings and doesn’t return an empty last item for a trailing newline.

How do I limit wrapped text to a few lines?

Pass max_lines and a placeholder to fill(), or use textwrap.shorten() for one line.

How do I write a long string on several lines in code?

Put adjacent string literals inside parentheses, or use triple quotes with textwrap.dedent().

Where is textwrap documented?

See textwrap in the Python docs.