views:

198

answers:

3

I'd like to slice a string up 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.

+1  A: 

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.

JimB
I like this because it doesn't break up or lose words longer than 15 characters, based on my very limited testing.
Dave Costa
+11  A: 
>>> import textwrap
>>> string = 'A string with words'
>>> textwrap.wrap(string,15)
['A string with', 'words']
ghostdog74
Is simple and works which ticks all my boxes!
chrism
+4  A: 

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.

jemfinch
Both good possibilities, but be aware that neither handles words longer than 15 characters very well `>>> s = 'A string with supercalifragilistic words'>>> textwrap.wrap(s,15) ['A string with s', 'upercalifragili', 'stic words']>>> re.findall(r'\b.{1,15}\b', s)['A string with ', ' words']`
Dave Costa
Define "very well." If you're wrapping text and a word is longer than the width of your terminal, you very much do want to split that word into chunks of your terminal's width, because that width is a hard limit.
jemfinch