HackerRank Python: Text Wrap Solution

Table of Contents

Question

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)

				
			
  1. The function wrap takes the input string and the maximum width as parameters.

  2. It initializes an empty string wrapped_string to store the wrapped string.

  3. It uses a for loop to iterate over the input string in steps of max_width. The loop variable i represents the starting index of each substring.

  4. Inside the loop, it appends the substring from index i to i+max_width to the wrapped_string and adds a newline character \n at the end to indicate the line break.

  5. Finally, it returns the wrapped_string containing the wrapped paragraph.

  6. In the main code, the input string and the maximum width are read from the user.

  7. The wrap function is called with the input string and the maximum width, and the result is stored in the result variable.

  8. The result is printed as the output.

If you find anything wrong in this Solution, feel free to reach us in the comment section.

Sharing Is Caring:

Leave a Comment