Solve Word Wrap Problem in Python

Hello Everyone! In this tutorial, we are going to learn how to solve word wrap problem in Python. Word wrapping is nothing but splitting the sequence of words into separate lines based on the given width. To understand this, Let’s see some examples.

Example – 1:

String: I have a book.

Line width: 5

Output:

I have

a book

One important thing is the count of the letters should be less than or equal to the given width. So, given a sequence of words, we have to break the sequence into separate lines and print those lines in orderly.

Python Implementation

def word_wrapper(string, width):
    new_string=""
    while len(string)>width:
        #find the position of nearest whitespace char to left of "width"
        index=width-1
        #check the char in the index of string of given width
        #if it is space then continue
        #else reduce the index to check for the space.
        while not string[index].isspace():
            index=index-1
        #remove the line from original string and add it to the new string
        line=string[0:index] + "\n"#separated individual linelines
        new_string=new_string+line#add those line to new_string variable
        string=''+string[index+1:]#updating the string to the remaining words
    #finally string will be left with less than the width.
    #adding those to the output
    return new_string+string
word_to_be_wrapped = "Learn coding. happy coding. Codespeedy helps you to learn coding. It provides coding solutions along with various IT services ( web development, software development etc )."
print(word_wrapper(word_to_be_wrapped,30))

Now we have to call the function with the assigned string and width

Testcase1:

word_to_be_wrapped = "Learn coding. happy coding. Codespeedy helps you to learn coding. It provides coding solutions along with various IT services ( web development, software development etc )."
print(word_wrapper(word_to_be_wrapped,30))

Output:

Learn coding. happy coding.
Codespeedy helps you to learn
coding. It provides coding
solutions along with various
IT services ( web
development, software
development etc ).

Hope this gives you a better understanding to solve word wrap problem in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *