Python program to wrap a text into paragraph with width w


Suppose we have a string s and width w. We have to wrap this text into a paragraph with width w. This can be done very easily with fill() function present inside textwrap library. So we have to import textwrap library first.

So, if the input is like s = "The quick brown fox jumps over the lazy dog" w = 9, then the output will be

The quick

brown fox

jumps

over the

lazy dog

To solve this, we will follow these steps −

  • take the string into s

  • take width into w

  • call textwrap.fill(s, w) by passing s as the first argument, and w as the second argument

Example

Let us see the following implementation to get better understanding

import textwrap
def solve(s, w):
   return textwrap.fill(s, w)

s = "The quick brown fox jumps over the lazy dog"
w = 9
print(solve(s, w))

Input

"The quick brown fox jumps over the lazy dog", 9

Output

The quick
brown fox
jumps
over the
lazy dog

Updated on: 11-Oct-2021

638 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements