The dedent() function

The dedent() is another function of the textwrap module. This function removes the common leading whitespaces from every line of your text.  

The syntax for this function is as follows:

 textwrap.dedent(text)

text is the text to dedent.

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

import textwrap

str1 = '''
Hello Python World This is Python 101
Scripting language
Python is an interpreted high-level programming language for general-purpose programming.
'''
print("Original: ", str1)
print()

t = textwrap.dedent(str1)
print("Dedented: ", t)

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

student@ubuntu:~/work$ python3 dedent_example.py

Hello Python World This is Python 101
Scripting language

Python is an interpreted high-level programming language for general-purpose programming.

In the preceding example, we created a str1 string variable. Then we used textwrap.dedent() to remove the common leading whitespaces. Tabs and spaces are considered whitespaces, but they are not equal. Therefore, the only common whitespace, which in our case is tab, is removed.

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

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