Navbar menu

HackerRank Python Solution - Strings - Text Wrap

  • 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.
  • the wrap has the following parameters:
    • 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, maxwidth.
Constraints:
  • 0 < len(string) < 1000
  • 0 < len(maxwidth.) < len(string)
Sample Input:

ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
Sample Output:

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
Solution:

import textwrap
    
def wrap(string, max_width):

    ans = textwrap.fill(string, max_width)
    return ans

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)
Disclaimer: The problem statement is given by hackerrank.com but the solution is generated by the Geek4Tutorial admin. If there is any concern regarding this post or website, please contact us using the contact form. Thank you!

No comments:

Post a Comment