Why isn't SPLIT splitting my strings

Duncan Booth duncan.booth at invalid.invalid
Sun Nov 19 11:35:33 CET 2006

"ronrsr" <ronrsr at gmail.com> wrote:

> I'm trying to break up the result tuple into keyword phrases.  The
> keyword phrases are separated by a ;  -- the split function is not
> working the way I believe it should be. Can anyone see what I"m doing
> wrong?

I think your example boils down to:

>>> help(str.split)
Help on method_descriptor:

    S.split([sep [,maxsplit]]) -> list of strings
    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator.

>>> s = 'Antibiotics, Animals'
>>> s.split('; ()[]"')
['Antibiotics, Animals']

This is what I expect. The separator string '; ()[]"' does not occur 
anywhere in the input string, so there is nowhere to split it.

If you want to split on multiple single characters, then either use 
re.split and filter out the separators, or use string.translate or 
str.replace to replace all of the separators with the same character and 
split on that. e.g.

>>> def mysplit(s):
	s = s.replace(' ', ';')
	s = s.replace('(', ';')
	s = s.replace(')', ';')
	s = s.replace('[', ';')
	s = s.replace(']', ';')
	s = s.replace('"', ';')
	return s.split(';')

>>> mysplit(s)
['Antibiotics,', 'Animals']

which still looks a bit weird as output, but you never actually said what 
output you wanted.

More information about the Python-list mailing list