String split

Peter Otten __peter__ at web.de
Tue Mar 28 18:55:13 CEST 2006


Michele Petrazzo wrote:

> Just a question about that "different algorithm", because it force the
> developer to do other work for make the "split" result more "logically
> compatible":
> 
> S = "" # this can become from an external source like config parser
> 
> for s n S.split():
>     do the work... # don't go inside
> 
> that isn't "compatible", so python split it into two different methods
> the string, with:
> 
> for s n S.split(','):
>     do the work... # run one time into this

No question.

>>> def split_any(s, seps):
...     for sep in seps:
...             parts = s.split(sep)
...             if len(parts) > 1:
...                     return parts
...     raise ValueError
...
>>> split_any(" alpha beta ", [",", None])
['alpha', 'beta']
>>> split_any("alpha,beta", [",", None])
['alpha', 'beta']
>>> split_any("alpha_beta", [",", None])
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 6, in split_any
ValueError

The answer :-)

Seriously, I think you have to be a bit more explicit on what you want to
know.

Peter




More information about the Python-list mailing list