Formatting Text Paragraphs in python is quick and easy. In fact, it’s so easy, you can learn it in a quickie in 5 minutes.
textwrap is a useful tool when it comes to formatting text paragraphs. You can wrap text by setting a maximum amount of characters, shorten text and other useful things.
I’m not quite sure for what purpose this will be useful other than just making the text fit into a box or maybe just for the fun of it (haha so much fun). One method of the
textwrap module is
fill. It returns a string with a newline on a set width. For example
print(textwrap.fill(para, width=50)) (with para being a variable) will print out a text in which every line consists of a maximal amount of 50 columns followed by a break. You can test it in the box below:
A similar function is
wrap. It formats the text to lines of a set width, too. But instead of returning a string, you get a list of strings. Each Item in the list being a line.
You can also shorten a text to a certain length with the function
shorten (who would have thought :-P):
What the functions above have in common is, that they wont break your words! If the length of a line or sentence exceeds the set width, the last word will be on the next line (or shown as