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.
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.
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 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.
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)
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