How To Wrap Text In Python

In this tutorial, we will learn how to wrap text in Python using a library called textwrap. This is useful for formatting long text in a way that makes it more manageable to read.

By the end of this tutorial, you will know how to split a large string into smaller chunks that can be easily displayed in a fixed-width console or any other limited-width situation.

Step 1: Import the textwrap library

First, we need to import the textwrap library which is included in the Python standard library. Add the following line at the beginning of your.py script:

Step 2: Prepare the text to be wrapped

Now let’s define some text that we want to wrap. In this example, we will use a quote by the famous philosopher Socrates:

This quote is 58 characters long, which is relatively small compared to large paragraphs. But for demonstration purposes, let’s wrap it into smaller lines.

Step 3: Use the wrap() function to wrap the text

The wrap() function takes two arguments:

  1. The text you want to wrap (the string variable)
  2. The width of the lines you want to wrap the text into

Here, we will wrap the text into 20 characters per line:

The wrap() function returns a list of strings, where each string is a line of the wrapped text. To see the result, we can print the wrapped_text variable:

The output will be:

The only true wisdom
is in knowing you know
nothing.

Now, the text has been split into three lines, with a maximum of 20 characters per line.

Step 4: Use the fill() function for a simpler solution

Instead of using the wrap() function and then joining the lines with a newline, we can use the fill() function, which is a more straightforward way to achieve the same result:

This will produce the same output as before:

The only true wisdom
is in knowing you know
nothing.

Full code

Conclusion

In this tutorial, we learned how to wrap text in Python using the textwrap library. By using either the wrap() or fill() functions, you can now split large strings into smaller chunks, making them more readable and manageable. This is especially useful when displaying text in fixed-width console applications or other limited-width situations.