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:
1 |
import textwrap |
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:
1 |
text = "The only true wisdom is in knowing you know nothing." |
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:
- The text you want to wrap (the string variable)
- The width of the lines you want to wrap the text into
Here, we will wrap the text into 20 characters per line:
1 |
wrapped_text = textwrap.wrap(text, 20) |
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:
1 |
print("\n".join(wrapped_text)) |
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:
1 2 |
filled_text = textwrap.fill(text, 20) print(filled_text) |
This will produce the same output as before:
The only true wisdom is in knowing you know nothing.
Full code
1 2 3 4 5 6 7 8 9 |
import textwrap text = "The only true wisdom is in knowing you know nothing." wrapped_text = textwrap.wrap(text, 20) print("\n".join(wrapped_text)) filled_text = textwrap.fill(text, 20) print("\n" + filled_text) |
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.