[Tutor] Split string on 2 delimiters ?

Kent Johnson kent37 at tds.net
Thu Aug 7 23:42:00 CEST 2008

On Thu, Aug 7, 2008 at 5:25 PM, dave selby <dave6502 at googlemail.com> wrote:
> Hi all,
> Is there a neat way to split a string on either of two delimiters ie
> space and comma

Use re.split():

In [1]: import re
In [2]: data = 'tom,dick harry'
In [4]: re.split(r'[, ]', data)
Out[4]: ['tom', 'dick', 'harry']

Since you have the full power of re to match your delimiter you could
for example allow comma, space or both:
In [6]: re.split(r', *| +', 'tom, dick,harry and bill')
Out[6]: ['tom', 'dick', 'harry', 'and', 'bill']


More information about the Tutor mailing list