Hanwool Codes RSS Tag Admin Write Guestbook
2023-02-17 04:32:12

Text Wrap | HackerRank

 

Text Wrap | HackerRank

Wrap the given text in a fixed width.

www.hackerrank.com

 

Goal

 

You are given a string S and width W.

Your task is to wrap the string S into a paragraph of width W.

 

Solution

 

You need to use textwrap module in python.

In textwrap, the function "wrap" is to wrap the string to the specified maximum width by breaking it into multiple lines.

The resulting lines are stored as a list in s_wrap_list. 

'\n'.join() function to return a string by joining the elements of the list with a newline character.

 

import textwrap

def wrap(string, max_width):
    
    s_wrap_list = textwrap.wrap(string, max_width)
    
    return '\n'.join(s_wrap_list)

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)
Hanwool Codes. Designed by 코딩재개발.