HackerRank Solution: Python Text Wrap [3 Methods]


Written by - Bashir Alam
Reviewed by - Deepak Prasad

Question: Text Wrap [Python Strings]

You are given a string S and width w.
Your task is to wrap the string into a paragraph of width w.

Function Description

Complete the wrap function in the editor below.

wrap has the following parameters:

  • string string: a long string
  • int max_width: the width to wrap to

Returns

string: a single string with newline characters ('\n') where the breaks should be
Input Format

The first line contains a string, string.
The second line contains the width, max width.

Constraints

  • 0< len(string) < 1000
  • 0 max width < len(string)

Sample Input 0

ABCDEFGHIJKLIMNOQRSTUVWXYZ
4

Sample Output 0

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

 

Possible Solutions

Let us now jump into the possible solutions to solve the given problem. The following code is already given in the editor of the hacker rank:

import textwrap

def wrap(string, max_width):
    return

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

Now let us go to the solutions:

 

Solution-1: Using for loop

First, let us see how we can solve the problem using the for loop.

import textwrap

def wrap(string, max_width):
    
    convert = list(string)
    
    lines = []
    line = ""
    
    for i in convert:
        if len(line) < max_width:
            line += i
            
        else:
            lines.append(line)
            line = i
            
    lines.append(line)
    
    return "\n".join(lines)

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

This solution is a function called wrap which takes two inputs, a string and an integer max_width, and returns the string with each line having a maximum length of max_width. The input string is first converted to a list of characters, and then the characters are iteratively added to a line string until it reaches the maximum width. The current line is then added to a list of lines and a new line string is created. This process continues until all the characters have been processed. Finally, the lines are joined with newline characters and returned as the final output. The code also has a conditional statement that calls the wrap function with inputs taken from the user when the code is executed as the main module.

 

Solution-2: Using textwrap module

Let us now use the textwrap module to solve the problem.

import textwrap

def wrap(string, max_width):
    wrapresult = textwrap.fill(string,max_width)
    return wrapresult
if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

Similar to the previous solution, this solution also has a function called wrap which takes two inputs, a string and an integer max_width, and returns the string with each line having a maximum length of max_width. The code makes use of the fill method from the textwrap module to perform the wrapping of the input string. The fill method takes in the input string and the maximum width, and returns the string with each line having a maximum length of the specified width. The wrap function then returns the result of the fill method as its final output.

 

Solution-3: Using join() method

We can use the join() method along with the textwrap module to solve the problem.

import textwrap

def wrap(string, max_width):
    wrapresult = textwrap.fill(string,max_width)
    return wrapresult

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

Unlike the previous code, this code makes use of the TextWrapper class from the textwrap module. The TextWrapper class provides more advanced options for text wrapping and formatting compared to the fill method. In this code, a TextWrapper object is created with the desired maximum width, and the input string is wrapped using the wrap method of the TextWrapper object. The returned result is a list of words, which is then joined using the newline character and returned as the final output. In essence, this code provides more control and customization over the wrapping process compared to the previous code which used the simple fill method.

 

Summary

In this short article, we discussed how we can solve the Text Wrap problem. We covered three different methods to solve the problem and explained each solution.

 

Further Reading

Question on Hacker Rank: Python Text Wrap [Strings]

 

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in OCR, text extraction, data preprocessing, and predictive models. You can reach out to him on his Linkedin or check his projects on GitHub page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment