How to split string

Tim Chase python.list at tim.thechases.com
Wed Dec 5 09:34:07 EST 2007


> In other words, the string should be split at every 10th possition but
> if the 10th character is space, then the string must be split at the
> nearest space before the 10th possition.
> 
> It could be better explained if the length of split strings will be
> 20.
> 
> S='this is just a random sequence of letters courtesy of monkeys on
>> typewriter.'
> 
> Results:
> 
> this is just a
> random sequence of
> letters courtesy of
> monkeys on
> typewriter.'
> 
> Any idea how to do that?

As mentioned previously, it sounds like you're looking for the 
built-in "textwrap" module:

 >>> s = "this is just a random sequence of letters courtesy of 
monkeys on typewriter."
 >>> import textwrap
 >>> print textwrap.fill(s, 20)
this is just a
random sequence of
letters courtesy of
monkeys on
typewriter.

http://docs.python.org/lib/module-textwrap.html

The Python library has already done all the heavy lifting--no 
need to re-invent the wheel.

-tkc








More information about the Python-list mailing list