Textwrap - Text wrapping and filling in Python

PythonServer Side ProgrammingProgramming

The textwrap module provides TextWrapper class that performs wrapping or filling. It has convenience functions for the same purpose.

wrap(text)

Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

fill(text)

Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph.

>>> sample_text = '''
The textwrap module provides some convenience functions, as well as TextWrapper class
that does all the work. If you’re just wrapping or filling one or two text strings,
the convenience functions should be good enough; otherwise, you should use an instance
of TextWrapper for efficiency.
'''
>>> import textwrap
>>> for line in (textwrap.wrap(sample_text, width = 50)):
print (line)

The textwrap module provides some convenience
functions, as well as TextWrapper class that
does all the work. If you’re just wrapping or
filling one or two text strings, the
convenience functions should be good enough;
otherwise, you should use an instance of
TextWrapper for efficiency.

Fill example

>>> textwrap.fill(sample_text, width = 50)
' The textwrap module provides some convenience\nfunctions, as well as TextWrapper class that\ndoes all the work. If you’re just wrapping or\nfilling one or two text strings, the\nconvenience functions should be good enough;\notherwise, you should use an instance of\nTextWrapper for efficiency.'
raja
Published on 16-Apr-2019 15:46:40
Advertisements