Enhance Text Presentation in Python with Textwrap Module

Posted by Afsal on 17-May-2024

Hi Pythonistas!

Today we will learn about a new module named textwrap. Python's Textwrap module provides a versatile toolkit for formatting text in various styles, making it an invaluable asset for developers. In this post, we'll delve into the capabilities of the Textwrap module and illustrate its usage with practical examples.

code 

import textwrap

text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

Text Wrapping

Wrap text to fit within 30 characters per line

code

wrapped_lines = textwrap.wrap(text, width=30)

print("Text Wrapping Example:")

for line in wrapped_lines:
    print(line)

Output

Text Wrapping Example:

Lorem ipsum dolor sit amet,

consectetur adipiscing elit.

Sed do eiusmod tempor

incididunt ut labore et dolore

magna aliqua.

Text Filling

Fill text to fit within 50 characters per line

Code

filled_text = textwrap.fill(text, width=50)

print("\nText Filling Example:")

print(filled_text)

Output

Text Filling Example:

Lorem ipsum dolor sit amet, consectetur adipiscing

elit. Sed do eiusmod tempor incididunt ut labore

et dolore magna aliqua.

Indentation Control

Indent the text with a prefix

Code

indented_text = textwrap.indent(filled_text, prefix=">> ")

print("\nIndented Text Example:")

print(indented_text)

Output

Indented Text Example:

>> Lorem ipsum dolor sit amet, consectetur adipiscing

>> elit. Sed do eiusmod tempor incididunt ut labore

>> et dolore magna aliqua.

Shorten

Code

short_text = textwrap.shorten(text, 20)

print("\n short text: ")

print(short_text)

Output

short text:

Lorem ipsum [...]

Here after width [...] is shown we can replace the placeholder with other character also

Code

short_text = textwrap.shorten(text, 20, placeholder="---")

print("\nshort text: ")

print(short_text)

Output

short text:

Lorem ipsum dolor ---

Dedent

Dedent remove the indendation on a text

code

text = """

    This is an indended text

    This is another text

"""

print('Original text: ', text)

print('Dedented text: ', textwrap.dedent(text))

Output

Original text:  

    This is an indended text

    This is another text

Dedented text:  

This is an indended text

This is another text

These are the basics of this package; you can refer the official documentation for more details. 

I hope you have learned something from this post. Please share your valuable suggestions with afsal@parseltongue.co.in