I'd like to split a string in a similar way to .split()
(so resulting in a list) but in a more intelligent way: I'd like it to split it into chunks that are up to 15 characters, but are not split mid word so:
string = 'A string with words'
[splitting process takes place]
list = ('A string with','words')
The string in this example is split between 'with' and 'words' because that's the last place you can split it and the first bit be 15 characters or less.
>>> import textwrap
>>> string = 'A string with words'
>>> textwrap.wrap(string,15)
['A string with', 'words']
You can do this two different ways:
>>> import re, textwrap
>>> s = 'A string with words'
>>> textwrap.wrap(s, 15)
['A string with', 'words']
>>> re.findall(r'\b.{1,15}\b', s)
['A string with ', 'words']
Note the slight difference in space handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With