Text Wrap of given string and given width using Python
In this Python tutorial, we will learn to text wrap of a given string and given width using Python. Easy and understandable Python code snippet is also provided. We hope it will help you to understand how easily you can do text wrap of a string in Python. If you don’t know what is text wrap then this post will also help you to understand that.
TEXT WRAP of a string in Python
Text Wrap of the input string:
- The user first inputs a non-spaced string.
- Then, in the second line, the user inputs the permissible width for each row.
- The output will execute wrapped text.
The header file that plays the key role in this code: textwrap
For example:
If the user inputs abcd in the first line and 2 in the second line, then the output will be:
ab cd
Now let’s take a look at the code snippet:
PROGRAM: to text wrap of a given string and given width in Python
s=input("Input Non-spaced String: ") #input non-spaced string w=int(input("Width: ")) #input width of the text wrap from textwrap import fill #input fill function from textwrap library print(fill(s,w)) #print output
OUTPUT 1:
Input Non-spaced String: abcdefghijklmnopqrstuvwxyz Width: 4 abcd efgh ijkl mnop qrst uvwx yz
OUTPUT 2:
Input Non-spaced String: ABCDEFGHIJKLMNOPQRSTUVWXYZ Width: 5 ABCDE FGHIJ KLMNO PQRST UVWXY Z
Also Read:
Leave a Reply