Python Glossary Русский

all Python 3textwrapfunction

textwrap.fill

wrapping

Like wrap(), but return a single string with newlines.

Syntax

textwrap.fill(text, width=70)

The trap is replace_whitespace, on by default: newlines and tabs inside the text become spaces, so a multi-paragraph string comes back glued into one block. Split on blank lines and fill each paragraph separately if the structure matters. Note also that text is merely wrapped, never justified to the right margin.

Examples

import textwrap
print(textwrap.fill('a b c', width=10))   # → a b c
print(repr(textwrap.fill('one two three four', width=10)))  # → 'one two\nthree four'
print(repr(textwrap.fill('one two three', width=12, initial_indent='* ')))  # → '* one two\nthree'
print(textwrap.fill('a b c d', width=10) == '\n'.join(textwrap.wrap('a b c d', width=10)))  # → True
print(repr(textwrap.fill('', width=10)))  # → ''

See also

Open in the full glossarydocs.python.orgReport an inaccuracy