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 u
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.
You're probably looking to use a regex. The python re module has a split
function, but I think you would be better served by simply matching groups.
>>> re.findall(r'(.{,15})\s(.*$)', 'A string wth words')
[('A string wth', 'words')]
[Edit] sorry, missed the point where you want multiple chunks. I was going to put a more complex regex in here, but the textwrap module cited above is made for this. I'll leave extending the regex as an exercise for you if you choose.
>>> import textwrap
>>> string = 'A string with words'
>>> textwrap.wrap(string,15)
['A string with', 'words']