Textwrap – Text Wrapping and Filling in Python

The Strings used in Python must be wrapped and more precise to make the code more understandable. The text must be wrapped to fit the text on the screen according to the size. The wrapping string breaks the written text based on the number of characters in one line. The text needs to be wrapped to preserve word integrity and appear natural. The Python programming language provides a module, namely “Textwrap,” which is used for formatting and wrapping plain text. It formats the text by altering the line breaks in the input paragraph, which helps make the text more precise and understandable. For wrapping the text, the module Textwrap provides a class “TextWrapper” that does a similar function of text wrapping with more efficiency.

Installing the Textwrap Library in Python

The textwrap library can be directly installed into the command prompt or by making a Python  environment by running this command:

py –m pip install textwrap3
Textwrap – Text Wrapping and Filling in Python

The library textwrap3 is an updated and compatible library with all versions of Python.

Importing Textwrap Module in Python

import textwrap3

Attributes of the TextWrapper Instance

  • width: The length of the longest wrapped line allowed for text wrapping. It is set to 70 by default.
  • expand_tabs: Using this, the tab characters are replaced by the white spaces if the value is set to TRUE. By default, it is TRUE.
  • tabsize:  It helps to change the tabsize when the expand_tabs is TRUE. By default, the value of tabsize is set to 8.
  • replace_tabsize: This helps to replace all the whitespaces in the text with a single space when its value is TRUE. By default, it is set to TRUE.
  • drop_whitespace: If any, it will drop the whitespace at the start or end of the wrapped text. It is set to TRUE by default.
  • Initial_indent: It adds the selected string at the first line of the wrapped text. By default, it is set to ‘ ’.
  • subsequent_indent: It adds the selected string to all the lines of wrapped text but not at the first line. By default, it is set to ‘ ’.
  • placeholder: It adds or appends the selected string at the end of the wrapped text if it has been shortened. By default, it is set to ‘ ’.
  • max_lines: It shows the number of lines after wrapping the text. If no value is given to it, then there is no limit for the lines. It is set to NONE by default.
  • broken_long_words: It breaks words longer than the width and fits them into a given width. It is set to TRUE by default. If the value is FALSE, then the words will not be broken and will be put on the line as it is.
  • break_on_hyphens: It is set as TRUE by default. The wrapping will happen on whitespaces following the hyphens in the compound words. If it is FALSE, then line breaks will be there only after the whitespaces.

Different Approaches for Text Wrapping in Python

1. textwrap.wrap()

    This method wraps the input string so that each line in the paragraph fits its given width. It returns a list of output-wrapped text.

    Syntax

    textwrap.wrap(text, width, **kwargs)

    where text is the input text to be wrapped

                 width is the length of the wrapped lines

                **kwargs are the arguments, if any

    Example 1: A simple program to wrap the text using textwrap.wrap() in Python.

    Code

    import textwrap3 as txt

    text = ("Let's wrap the following text:  Text wrapping in Python. The Strings used"       "in Python must be wrapped and more precise to make the code more" "understandable. The text must be wrapped to fit the text on the screen according to" "the size. The wrapping string breaks thewritten text based on the number of" "characters in one line. The text must be wrapped to preserve the word integrity" "and appear natural. The Python programming language provides a module, namely"   " “Textwrap,” which is used for formatting and wrapping plain text. It formats the" "text by altering the line breaks in the input paragraph, which helps make the text" more precise and understandable.")

    wrapped_output = txt.wrap(text)

    print("Total number of Wrapped Lines : {}".format(len(wrapped_output)))

    print("\n".join(wrapped_output))

    Output

    Total number of Wrapped Lines: 10

    Let's wrap the following text:  Text wrapping in Python. The Strings

    used in Python must be wrapped and more precise to make the code more

    understandable. The text must be wrapped to fit the text on the screen according to the size. The wrapping string breaks the written

    text based on the number of characters in one line. The text needs to

    be wrapped to preserve word integrity and appear natural. The Python

    programming language provides a module, namely “Textwrap,” which is

    used for formatting and wrapping plain text. It formats the text by

    altering the line breaks in the input paragraph, which helps make the

    text more precise and understandable.

    First, the library textwrap is imported in this code, and an object txt is made. Then, a string is given, wrapped using textwrap.wrap().

    2. textwrap.fill()

    This method returns the wrapped text into a newline-separated string. Though it works similarly to the wrap() function, it does not return a text as a list. This function wraps the single paragraph entered in the text, producing a single string containing the wrapped paragraph.

    Syntax

    textwrap.fill(text, width, **kwargs)

    where text is the input text to be wrapped

                 width is the length of the wrapped lines

                **kwargs are the arguments, if any

    Example 2: A simple program to wrap the text using textwrap.fill() in Python.

    Code

    import textwrap3 as txt

    text1 = ("Using textwrap.fill() function. hello, I am using Python. Let's understand the topic of text wrapping.")

    str = txt.fill(text=text1) 

    print("Total number of Wrapped Lines : {}".format(len(str)))

    print (str)

    Output

    Total number of Wrapped Lines: 101

    Using textwrap.fill() function. Hello, I am using Python. Let's

    understand the topic of text wrapping.

    In this code, the text is wrapped but returning the wrapped text as a single line, not a list.

    3. textwrap.dedent()

    The dedent function helps to remove any common leading whitespace in the input string. It helps to use embedded multi-line strings or docstring. Along with this, it removes the formatting of the code itself.

    Syntax

    textwrap.dedent(text)

    where text is the input text to be wrapped

    Example 3: A simple program to wrap the text using textwrap.dedent() in Python.

    Code

    import textwrap as txt

    #wrap = txt.TextWrapper(width=50)

    str = '''

        hello    world

           I am

           using Python

         '''

    print(repr(str))  

    text = txt.dedent(str)

    print("\nWrapped text:\n", repr(text))

    Output

    '    hello    world\n       I am \n       using   python\n     '

    Wrapped text:

     'hello    world\n   I am \n   using   python\n'

    In this code, the dedent method has reduced whitespaces from the wrapped text.

    4. textwrap.shorten()

    This function collapses the whitespaces from the text and replaces them with single spaces. It will return the text after fitting it to the width. The shorten method truncates the input text to make the length of the text equal to the width.

    Syntax

    textwrap.shorten(text, width)

    where text is the input text to be wrapped

                 width is the length of the wrapped lines

    Example 4: A simple program to wrap the text using textwrap.shorten() in Python.

    Code

    import textwrap3 as txt

    text = ("Let's wrap the following text: Text wrapping in Python. The Strings used in "

    "Python must be wrapped and more precise to make the code more understandable. "

    "The text must be wrapped to fit the text on the screen according to the size. The"

    "wrapping string breaks the written text based on the number of characters in one line.")

    wrapped_output = txt.shorten(text, width =60)

    print("Total number of Wrapped Lines: {}".format(len(wrapped_output)))

    print(wrapped_output)

    Output

    Total number of Wrapped Lines: 53

    Let's wrap the following text: Text wrapping in [...]

    In this code, the string is shortened according to the width of the text, and then at the end […] is added.

    5. textwrap.indent()

    This function adds a prefix at the beginning of each line. It will take an input of text spread into multiple lines and, add the prefix at the beginning of the selected line, then returns the wrapped text.

    Syntax

    textwrap.indent(text, prefix)   

    where text is the input text to be wrapped

                prefix is the character or any prefix which is to be added before the wrapping

    Example 5: A simple program to wrap the text using textwrap.indent() in Python.

    Code

    import textwrap as txt

    #wrap = txt.TextWrapper(width=50)

    str = '''

    hello world

    I am

    using Python

         '''

    print(str)

    text = txt.indent(str, '# ')

    print("Wrapped Text:\n", text)

    Output

    hello world

    I am

    using Python

    Wrapped Text:

    # hello world

    # I am

    # using Python

    In this code, ‘# ’ is added at the beginning of each line.