Splitting a string

Xie Yanbo xieyanbo at gmail.com
Tue Feb 14 02:59:38 EST 2006


On 2/14/06, Nico Grubert <nicogrubert at gmail.com> wrote:
> Dear Python users,
>
> I'd like to split a string where 'and', 'or', 'and not' occurs.
>
> Example string:
> s = 'Smith, R. OR White OR Blue, T. AND Black AND Red AND NOT Green'
>
> I need to split s in order to get this list:
> ['Smith, R.', 'White', 'Blue, T.', 'Back', 'Red', 'Green']
>
> Any idea, how I can split a string where 'and', 'or', 'and not' occurs?

RE module can do this:
>>> import re
>>> s = 'Smith, R. OR White OR Blue, T. AND Black AND Red AND NOT Green'
>>> r = re.split('(?i)\s*(and\s*not|and|or)\s*', s)
>>> [x[1] for x in enumerate(r) if (x[0]+1) % 2]
['Smith, R.', 'White', 'Blue, T.', 'Black', 'Red', 'Green']


More information about the Python-list mailing list