Reputation: 11
You are given a string S
and width w
.
Your task is to wrap the string S
into a paragraph of width w
.
Input Format
The first line contains a string, S
.
The second line contains the width, w
.
Sample Input
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
Sample Output
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
I tried the code, but didn't get the required result. As 2 extra lines are coming in the output. Also Note: Last 4 lines in the code is immutable(not to be changed)
import textwrap
def wrap(string, max_width):
y=max_width
z=0
for i in range(0,len(string),y):
print(string[0+z:y+z])
z+=max_width
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
Upvotes: 0
Views: 1679
Reputation: 25
(one extra line is coming)
import textwrap
def wrap(string, max_width):
i=0
j=max_width
n=(len(string)//max_width)+(len(string)%max_width)
for l in range(0,n-1):
print(string[i:j:])
i=i+max_width
j=j+max_width
return
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
Upvotes: 0
Reputation: 21
Try this its a bit smaller and less sophisticated
import textwrap
def wrap(string, max_width):
text = textwrap.fill(string,max_width)
return text
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
Upvotes: 1
Reputation: 11
a="ABCDEFGHIJKLIMNOQRSTUVWXYZ"
k=0
h=4
for i in range(7):
print(a[k:h])
k=h
h=h+4
# only consumes 95bytes.
Upvotes: 1
Reputation: 12027
your idea was right, but you didnt build up a string in your function to return to the calling code for the main code to print it.
def wrap(string, max_width):
y=max_width
z=0
return_string = "" #Create an empty string that we will build as we go
for i in range(0,len(string),y):
return_string += string[0+z:y+z] + "\n" #append the chars to the string with a new line
z+=max_width
return return_string
if __name__ == '__main__':
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)
This could also be written as a list comprehension and joined with new lines
def wrap(string, max_width):
return "\n".join([string[i:i+max_width] for i in range(0, len(string) - 1, max_width)])
Upvotes: 0