Skip to content
Rezha Julio
Go back

Format text paragraphs with textwrap

1 min read

Python’s textwrap module is useful for rearranging text, e.g. wrapping and filling lines.

Import the module:

import textwrap

Wrap the text in the string “parallel”, so that all lines are a maximum of x characters long:

# When x = 2
textwrap.wrap("parallel", width=2)
# Output:
# ['pa', 'ra', 'll', 'el']
# When x = 4
textwrap.wrap("parallel", width=4)
# Output:
# ['para', 'llel']

Returns a list of lines (without trailing newlines).

If we would like to include trailing newlines (\n) after a each string of a certain width we can either use the following syntax:

'\n'.join(textwrap.wrap('text', width=2))
# Output:
# 'te\nxt'

Or we can use the fill method implemented in textwrap module:

textwrap.fill("text", width=2)
# Output:
# 'te\nxt'

Collapse and truncate a text to width :

print(textwrap.shorten("Hello world!", width=12))
# Hello world!
print(textwrap.shorten("Hello world!", width=11))
# Hello [...]

The last words are dropped if the text is longer than the width argument. Other useful methods like indent and dedent are available in this module.


Related Posts


Previous Post
Get the Most of Floats
Next Post
Unicode Character Database at Your Hand