The wrap() function

The wrap() function is used to wrap an entire paragraph in to a single string. The output will be a list of output lines.

The syntax is textwrap.wrap(text, width):

  • text: Text to wrap.
  • width: Maximum length allowed of a wrapped line. The default value is 70.

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

import textwrap

sample_string = '''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.'''

w = textwrap.wrap(text=sample_string, width=30)
print(w)

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

student@ubuntu:~/work$ python3 wrap_example.py
['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.']

In the preceding example, we used the textwrap module of Python. First, we created a string named sample_string. Next, using the TextWrapper class we specified the width. Next, using the wrap function the string was wrapped to the width of 30. And next, we printed the lines.

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

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