Wrap Text in Python using - textwrap module


If you have a use-case where you want to wrap text that you output using the Python code on the console or a Jupyter Notebook, you can make use of the textwrap module.

We can make use of the width attribute to set the width of each line where you want to wrap the text.


Examples:

import textwrap
  
text = """This is a long sentence that I would like to wrap for this Python Program output. Let's see if it works."""
  
text_wrapper = textwrap.TextWrapper(width=15)
  
wrapped_text_list = text_wrapper.wrap(text=text)
  
for wrapped_line in wrapped_text_list:
    print(wrapped_line)
Wrap Text in Python Example 1
Wrap Text in Python Example 2

You can expore more about this module here: https://docs.python.org/3/library/textwrap.html

-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap