Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do textwrap.wrap() & textwrap.fill() exactly work in python 2?

>>> import textwrap
>>> string = "This is a very very very very very long string."
>>> print textwrap.wrap(string,8)
>>> print textwrap.fill(string,8)

Output:

['This is', 'a very', 'very', 'very', 'very', 'very', 'long', 'string.']

This is

a very

very

very

very

very

long

string.

I get the fact that textwrap.wrap() gives me a list and textwrap.fill gives me a string. In documentation its said, "Wraps the single paragraph in text (a string) so every line is at most width characters long".

But I don't understand then why isn't the length of each element of the list formed by textwrap.wrap(), 8 if 8 is passed as the width parameter. WHy is it sometimes 7,6,etc.

Similarly, I don't understand why in case of textwrap.fill(), is the length of each line = 8 characters (if width is passed as 8 or 5 if width is passed as 5). As in example,its sometimes, 7,6,4,etc. Why not exactly equal to the width. Because its said at most each line should be width characters long so, why does it break before using all the 8 characters available in line if with is passed as 8?

Shouldn't it be something like below:

>>> import textwrap
>>> string = "This is a very very very very very long string."
>>> print textwrap.fill(string,8)

OUTPUT:

This is

a very v

ery very

very ve

ry long

string.

like image 224
PyAndy Avatar asked Jun 28 '26 22:06

PyAndy


1 Answers

As the documentation stated:

Wraps the single paragraph in text (a string) so every line is at most width characters long. Returns a list of output lines, without final newlines.

textwrap only split words at word breaks (usually at spaces) and makes sure that each string doesn't go over the width limit. Note: it doesn't split at every width characters.

It is used to splitting strings into sections, with each section having the most possible number of words equal or less than width characters long, while not breaking any of the words.

like image 158
Taku Avatar answered Jun 30 '26 13:06

Taku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!