Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper word wrapping of long text

Tags:

python

I have a 1000 character long text string and I want to split this text in chunks smaller than 100 characters without splitting a whole word (99 characters are fine but 100 not). The wrapping/splitting should only be made on whitespaces:

Example:

text = "... this is a test , and so on..."
                              ^
                  #position: 100

should be splitted to:

newlist = ['... this is a test ,', ' and so on...', ...]

I want to get a list newlist of the text splitted properly into readable (not word-cropped) chunks. How would you do this?

like image 822
Johnny Avatar asked Dec 30 '25 01:12

Johnny


1 Answers

Use the textwrap module's wrap function. The below example splits the lines 10 characters wide:

In [1]: import textwrap

In [2]: textwrap.wrap("... this is a test , and so on...", 10)
Out[2]: ['... this', 'is a test', ', and so', 'on...']
like image 124
Joseph Victor Zammit Avatar answered Jan 01 '26 13:01

Joseph Victor Zammit