Table of Contents
ToggleQuestion
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.
wrap has the following parameters:
- string 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 < maxwidth < len(String)
Sample Input 0
ABCDEFGHIJKLIMNOQRSTUVWXYZ
4
Sample Output 0
ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
Solution
def wrap(string, max_width):
wrapped_string = ""
for i in range(0, len(string), max_width):
wrapped_string += string[i:i+max_width] + '\n'
return wrapped_string
# Read the input string and max_width
string = input().strip()
max_width = int(input().strip())
# Call the wrap function and print the result
result = wrap(string, max_width)
print(result)
The function
wrap
takes the input string and the maximum width as parameters.It initializes an empty string
wrapped_string
to store the wrapped string.It uses a
for
loop to iterate over the input string in steps ofmax_width
. The loop variablei
represents the starting index of each substring.Inside the loop, it appends the substring from index
i
toi+max_width
to thewrapped_string
and adds a newline character\n
at the end to indicate the line break.Finally, it returns the
wrapped_string
containing the wrapped paragraph.In the main code, the input string and the maximum width are read from the user.
The
wrap
function is called with the input string and the maximum width, and the result is stored in theresult
variable.The result is printed as the output.
If you find anything wrong in this Solution, feel free to reach us in the comment section.