split() with a separator set
Kevin Digweed
Kevin.Digweed at dial.pipex.com
Mon Jun 19 11:32:19 EDT 2000
"Igor V. Rafienko" wrote:
>
> Hi,
>
> I've just started learning Python, so, please bear with me.
>
> string.split() function takes (amongst other things) a separator
> argument, and the given string is split according to this separator.
> But what if I have several one-character separators? Obviously:
>
> # input looks like this: 'foo:bar|baz/zot'
> # I want [ 'foo', 'bar', 'baz', 'zot' ]
> string.split( src, ":|/" )
>
> doesn't work.
Try mapping the source characters in the set to a common character (the
first in the set), then splitting using that single character:
import string
def setsplit(src, sset=string.whitespace):
return string.split(string.translate(src, string.maketrans(sset,
sset[0]*len(sset))), sset[0])
.. I realise that sset[0] characters get 'translated' to sset[0]
characters, but I suspect that the implementation of CPython
string.translate (I haven't verified it) means that it's free anyway.
Or ... use 're'.
Kev.
More information about the Python-list
mailing list