The shorten() function

This function of the textwrap module is used truncate the text to fit in the specified width. For example, if you want to create a summary or preview, use the shorten() function. Using shorten(), all the whitespaces in your text will get standardized into a single space.

The syntax for this function is:

            textwrap.shorten(text, width)

Now we will see an example of shorten(). Create a shorten_example.py script and write the following content in it:

import textwrap

str1 = "Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace."

s = textwrap.shorten(str1, width=50)
print(s)

Run the script and you will get the output as follows:

student@ubuntu:~/work$ python3 shorten_example.py
Python is an interpreted high-level [...]

In the preceding example, we used the shorten() function to truncate our text and fit that text in a specified width. First, all the whitespaces truncated into the single space. If the result fited in the specified width, the result was displayed on the screen. If not, then the words of the specified width was displayed on the screen and the rest was placed in the placeholder.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset