Break text into lines by the number of characters

I have a text like:

'This is a line of text over 10 characters'

So that I needed to break into lines consisting of no more than 10 characters without breaking words, if I do not need (for example, a line with a job containing more than 10 characters).

The line above has turned into:

'This is a\nline of\ntext over\n10\ncharacters'

This is a pretty simple problem, but I would like to hear how people do it. I am going to start coding it and publish my solution after a while.

+5
source share
1 answer

You need textwrap

>>> import textwrap
>>> s = 'This is a line of text over 10 characters'
>>> textwrap.fill(s, width=10)
'This is a\nline of\ntext over\n10\ncharacters'
+16
source

All Articles