Python Reference ยท Standard Library: Math, Data and Text
The textwrap module
Reference for Python's textwrap module: wrap and fill long text to a width, shorten with placeholders, dedent triple-quoted strings and indent lines.
The textwrap module reshapes plain text. It can break a long paragraph into lines of a maximum width, collapse text to a single line of limited length, remove common leading whitespace from indented triple-quoted strings, and add a prefix to lines. It is ideal for command line output, help messages, log formatting and tidy multi-line strings in source code.
Width is counted in characters, not display columns, so wide characters such as many CJK glyphs may not line up in a terminal.
import textwrap print(textwrap.fill("A long sentence that needs wrapping.", width=20))
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
textwrap.wrap(text, width=70, **kwargs) textwrap.fill(text, width=70, **kwargs) textwrap.shorten(text, width, **kwargs) textwrap.dedent(text) textwrap.indent(text, prefix, predicate=None)
| Function | Description |
|---|---|
wrap |
Returns a list of lines, each at most width characters, without trailing newlines. |
fill |
Returns one string: the lines of wrap() joined with \n. |
shorten |
Collapses whitespace, then cuts at a word boundary so the result (with the placeholder) fits in width. The default placeholder is " [...]". |
dedent |
Removes the leading whitespace that all non-blank lines have in common. |
indent |
Adds prefix to the start of lines. By default whitespace-only lines are skipped; predicate overrides that. |
Common keyword options
| Option | Default | Effect |
|---|---|---|
initial_indent |
"" |
Prefix for the first line. |
subsequent_indent |
"" |
Prefix for all other lines. |
expand_tabs |
True |
Expand tabs to spaces (tab size 8) first. |
replace_whitespace |
True |
Turn each whitespace character into a single space. |
break_long_words |
True |
Split words longer than width. |
break_on_hyphens |
True |
Allow breaks after hyphens. |
drop_whitespace |
True |
Remove whitespace at line ends and starts (after indents). |
max_lines |
None |
Truncate the result to this many lines, ending with placeholder. |
placeholder |
" [...]" |
Text appended when output is truncated. |
For repeated use with the same options, create a textwrap.TextWrapper(**options) and call its wrap() and fill() methods.
Usage notes
widthincludes the indents. Awidth=30line withinitial_indent="* "leaves 28 characters for words.- Paragraphs are not preserved.
wrap()treats the whole string as one paragraph and turns newlines into spaces, so wrap each paragraph separately (for exampletext.split("\n\n")). shorten()can return only the placeholder (or raiseValueErrorif the width is smaller than the placeholder).dedent()and mixed tabs/spaces. Tabs and spaces are different characters, so mixing them can prevent any common prefix from being found.- Triple-quoted strings: start with
"""\(a backslash after the quotes) to avoid an empty first line, then calldedent(). indent()leaves lines that contain only whitespace unchanged unless you pass apredicate.- Not Unicode-width aware: combining marks and double-width characters count as one character each.
Related
str.join(),str.ljust(),str.splitlines(),string- Lessons: Strings, String formatting