Text Wrap in Python - HackerRank Solution

Text Wrap in Python - HackerRank Solution
Text Wrap in Python - HackerRank Solution


Problem :


Tutorial :

Textwrap :
The textwrap module provides two convenient functions: wrap() and fill().

textwrap.wrap()
The wrap() function wraps a single paragraph in text (a string) so that every line is width characters long at most.
It returns a list of output lines.
>>> import textwrap
>>> string = "This is a very very very very very long string."
>>> print textwrap.wrap(string,8)
['This is', 'a very', 'very', 'very', 'very', 'very', 'long', 'string.'] 

textwrap.fill()
The fill() function wraps a single paragraph in text and returns a single string containing the wrapped paragraph.
>>> import textwrap
>>> string = "This is a very very very very very long string."
>>> print textwrap.fill(string,8)
This is
a very
very
very
very
very
long
string.

Task :

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



Input Format :

The first line contains a string, S.
The second line contains the width, W.

Constraints :

  • 0 < len(s) < 1000
  • 0 < w < len(s)

Output Format :

Print the text wrapped paragraph.



Sample Input :

ABCDEFGHIJKLIMNOQRSTUVWXYZ
4

Sample Output :

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ



Solution :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Text Wrap in Python - HackerRank Solution
import textwrap

def wrap(string, max_width):
    # Text Wrap in Python - HackerRank Solution START
    return textwrap.fill(string,max_width)
    # Text Wrap in Python - HackerRank Solution END

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





Disclaimer :-
the above hole problem statement is given by hackerrank.com but the solution is generated by the codeworld19 authority if any of the query regarding this post or website fill the following contact form thank you.

Next Post Previous Post
2 Comments
  • chai123
    chai123 Saturday, April 02, 2022

    for without using text wrapping module we can write the code as follows:



    def wrap(s,m):
    s=s.strip()
    k=0
    for i in range(m,len(s),m):
    print(s[k:i])
    k=i
    return s[k:]

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

    • Anonymous
      Anonymous Tuesday, August 09, 2022

      You could also do:

      def wrap(string, max_width):
      x = ""
      y = ""
      for i in string:
      x += i
      if len(x) == max_width:
      y += x + "\n"
      x = ""
      y += string[-(len(string) % max_width):]
      return y

Add Comment
comment url