Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string using space delimiters and a maximum length

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.

like image 995
chrism Avatar asked Apr 12 '10 13:04

chrism


2 Answers

>>> import textwrap
>>> string = 'A string with words'
>>> textwrap.wrap(string,15)
['A string with', 'words']
like image 112
ghostdog74 Avatar answered Sep 21 '22 05:09

ghostdog74


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.

like image 39
jemfinch Avatar answered Sep 21 '22 05:09

jemfinch