Write a Python program to wrap a given string into a paragraph of given width
The program is using the Python's built-in textwrap module to wrap a given input string into paragraphs of a specified width.
- The program prompts the user to enter a string and the width of the paragraph that they want the string to be wrapped into. The input string is stored in the variable s, while the paragraph width is stored in the variable w.
- The strip() method is used to remove any leading or trailing white space from the user input for the paragraph width, to prevent any issues that may arise from extra spaces or tabs that may have been accidentally entered.
- The program then uses the textwrap.fill() function to wrap the input string s into paragraphs of width w. This function takes two arguments: the string to be wrapped, and the width of each paragraph. The wrapped string is then printed to the console using the print() function.
- The program also prints a line of dashes before the wrapped string to separate it from any previous output on the console. This is purely for visual clarity and is not required for the functionality of the program.
Source Code
import textwrap
s = input("Enter a String: ")
w = int(input("Enter the Width of the Paragraph: ").strip())
print("\n-------------Result---------------\n")
print(textwrap.fill(s,w))
Output
Enter a String: Tutor Joes Computer Education
Enter the Width of the Paragraph: 5
-------------Result---------------
Tutor
Joes
Compu
ter E
ducat
ion