The world’s leading publication for data science, AI, and ML professionals.

6 Fancy Built-In Text Wrapping Techniques in Python

Single-line of code makes your text "print-ready" in your application

Photo by Bob_Dmyt on Pixabay
Photo by Bob_Dmyt on Pixabay

Everyone knows that Python is famous for its comprehensive standard libraries. In most of the other Programming languages, we will have to implement many features using chunks by chunks of code. However, in Python, we can find that many of the fancy features are already implemented and we can use them out-of-the-box.

In this article, I’m going to introduce another Python built-in library "Text Wrapper" that can help us to produce "print-ready" wrapped text in our applications very easily. There is no need to install it, just import and use it as it comes with your Python3 as a standard library.

1. Basic Text Wrapping

Photo by SpencerWing on Pixabay
Photo by SpencerWing on Pixabay

As I stated in the introduction, you don’t need to install anything. Just import the library as follows.

import textwrap as tr

For demonstrating purposes, let’s define a string, which is a sentence that I copied from Wikipedia page for Python https://en.wikipedia.org/wiki/Python_(programming_language)

my_str = "Python is an interpreted, high-level and general-purpose programming language."

OK. This my_str is not a short sentence. Suppose your software UI or Webpage needs to display the text in a certain width. When the text is longer than the width, the text needs to be broken up into multiple lines. Of course, we don’t want to break it in exactly the length that equals the width because that may cause some words are partially at the end of the line and the other part starts in the next line. This is not considered a good reading experience from the user perspective.

The Text Wrap library comes to the rescue. Rather than implementing some complex logic to detect the word boundaries, we can easily use the following code to break the sentence.

lines = tr.wrap(my_str, width=30)

As shown, the sentence is broken up into 3 pieces. This is because we set the width=30, so the text will be wrapped before it reaches 30 to make sure it won’t go "overflow" in the UI. If we count the length of the 3 pieces, the lengths are 25, 30 and 21 respectively.

Therefore, Python TextWrapper is smart enough to recognise that the next word is long enough to make the current line go overflow, so it automatically puts it to the next line. That’s why we have 25 characters for the first line.

2. Print-Ready Text Wrapping

Photo by blickpixel on Pixabay
Photo by blickpixel on Pixabay

Well, you might think that it is still not convenience enough because we still need to loop the list to get the wrapped strings line by line to print as follows.

Yes, that’s why Python provided another function fill() exactly to make it more convenience.

The same string, rather than using tr.wrap(), we can use tr.fill() to get a single wrapped string with n inside, which is "print-ready".

tr.fill(my_str, width=30)

How convenient it is!

3. Truncate with Text Wrapper

Photo by Pexels on Pixabay
Photo by Pexels on Pixabay

Do we have to display everything on the application UI? Not always.

I bet you must have ever seen some truncated text in some software or websites. For example, the screenshot below is from Quora.com.

See that "…(more)" indicator? It let us know that there is more content inside but it won’t display everything for now. This is a sort of UI design concepts that is out of the scope of this article. However, if you want to imitate this behaviour using Python, one line of code is enough.

Let’s keep using the same string in the above examples. This time, we gonna use tr.shorten() function.

tr.shorten(my_str, width=30)

The string is automatically truncated and the overall length will be less than 30. Of course, if the width is long enough, or we can also say that the text is short enough, it will not be truncated.

tr.shorten(my_str, width=80)

So, we set the width=80 and the string is less than that. It won’t be truncated then.

Additionally, what if I’m not happy with the placeholder [...]? It is actually just a default placeholder, we can definitely customise it.

tr.shorten(my_str, width=30, placeholder=' ...(more)')

Then, we have got it exactly the same style as in Quora 🙂

4. Auto-Cleaning string

Photo by blickpixel on Pixabay
Photo by blickpixel on Pixabay

The Text Wrapper library cannot only wrap and truncate text, it can also fix your text if the format has some problems. This would be extremely convenient if your application is dealing with a lot of text from other sources and you want to format it before store it or display it.

Suppose we have another string, which is quite messy in terms of its format.

my_str2 = '''
    Python is an interpreted,
    high-level and general-purpose
    programming language.
'''

This is exactly the text we got from the above example, but with 2 whitespaces as the "common indentation" for every line. By using the dedent() function, we can easily get rid of them.

tr.dedent(my_str2)

Here it shows the difference between using and not using the dedent() function.

Of course, it works on any number of leading whitespaces, not just two.

5. Customised Auto-Indentation

Photo by Couleur on Pixabay
Photo by Couleur on Pixabay

Rather than getting rid of the indent from the multi-lined text, what if we want to add some indent? Yes, we can do that using Text Wrapper.

There is a function that acts as the opposite of dedent(), which is indent(). Suppose we have a piece of code as follows

some_code = '''
import textwrap as tr
print("hello world!")
for i in range(10):
    print(i)
'''

Look at the example below, it adds 2 whitespaces in front of every line.

tr.indent(some_code, '  ')

The screenshot shows the difference from the original string.

Well, I would agree that it doesn’t make too much sense at the moment. Why do we want to add leading whitespaces to the text? The following example might be more interesting then.

tr.indent(some_code, '>>> ')

Yes, don’t forget we can customise what is the string that is used for the indentation. Does it look like the Python console? Not 100%. The new lines without text were not added with the >>> prompt. Don’t worry, the indent() function takes another argument which will be a predicate to tell the program "whether this line should be added with the prefix".

tr.indent(some_code, '>>> ', lambda line: True)

Therefore, all the lines have the prompts now. It looks exactly like the Python console.

6. Reuse TextWrapper Instance

Photo by QuinceCreative on Pixabay
Photo by QuinceCreative on Pixabay

So far, we have introduced 5 different functions in the Text Wrapper library. In fact, these above functions will create a TextWrapper instance from the class automatically, and then apply the transformation of the text. Then, the instance will be disposed of.

When we have a number of strings that need to be wrapped, or we need some features that are defined only as a class method in TextWrapper rather than as a public function, we have to instantiate the TextWrapper class.

The good thing is that we can also reuse the instance for whatever times we need to.

wrapper = tr.TextWrapper(
    width=50, 
    initial_indent="- "
)

In the above code, we declared a Text Wrapper instance from the class and initialised the width with 50. Also, we defined an attribute initial_indent which will be added to all the "wrapped" text as their prefix.

Now, we need multiple sentences. These are also extracted from the same Wiki page.

my_strings = [
    "Python is an interpreted, high-level and general-purpose programming language.",
    "Python's design philosophy emphasizes code readability with its notable use of significant indentation.",
    "Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.",
    "Python is dynamically-typed and garbage-collected.",
    "It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming.",
    "Python is often described as a "batteries included" language due to its comprehensive standard library."
]

Then, let’s WRAP!

for s in my_strings:
    print(wrapper.fill(s))

Summary

Photo by klimkin on Pixabay
Photo by klimkin on Pixabay

In this article, I have introduced a Python built-in library "Text Wrapper". It can easily wrap the text for us to make sure all the lines are within a certain width. This is quite important in an application with UI so that the text won’t go overflow.

Not only wrapping text, but the library also provides a lot more features that are quite convenient, such as indent and decent. When we want to use the library to wrap the text with the same parameters, it would be better to instantiate the Text Wrapper class so that we can reuse the instance.

Join Medium with my referral link – Christopher Tao

If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)


Related Articles