s.split() on multiple separators

Tim Chase python.list at tim.thechases.com
Sun Sep 30 18:59:07 CEST 2007

> OK, so I want to split a string c into words using several different
> separators from a list (dels).
> I can do this the following C-like way:
>>>> c=' abcde abc cba fdsa bcd '.split()
>>>> dels='ce '
>>>> for j in dels:
> 	cp=[]
> 	for i in xrange(0,len(c)-1):
> 		cp.extend(c[i].split(j))
> 	c=cp
>>>> c
> ['ab', 'd', '', 'ab', '', '']

Given your original string, I'm not sure how that would be the
expected result of "split c on the characters in dels".

While there's a certain faction of pythonistas that don't esteem
regular expressions (or at least find them overused/misused,
which I'd certainly agree to), they may be able to serve your
purposes well:

  >>> c=' abcde abc cba fdsa bcd '
  >>> import re
  >>> r = re.compile('[ce ]')
  >>> r.split(c)
  ['', 'ab', 'd', '', 'ab', '', '', 'ba', 'fdsa', 'b', 'd', '']

given that a regexp object has a split() method.


More information about the Python-list mailing list