Problem splitting a string

Mike Meyer mwm at
Sat Oct 15 08:07:51 CEST 2005

Robert Kern <robert.kern at> writes:
> Anthony Liu wrote:
>> I have this simple string:
>> mystr = 'this_NP is_VL funny_JJ'
>> I want to split it and give me a list as
>> ['this', 'NP', 'is', 'VL', 'funny', 'JJ']
> You could use regular expressions as Jason Stitt mentions, or you could
> replace '_' with ' ' and then split.
> In [2]: mystr = 'this_NP is_VL funny_JJ'
> In [3]: mystr.replace('_', ' ').split()
> Out[3]: ['this', 'NP', 'is', 'VL', 'funny', 'JJ']

A third alternative is to split once, then split the substrings a
second time and stitch the results back together:

>>> sum([x.split('_') for x in mystr.split()], [])
['this', 'NP', 'is', 'VL', 'funny', 'JJ']

Which is probably slow. To bad extend doesn't take multiple arguments.

Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list