faqts : Computers : Programming : Languages : Python : Common Problems : Strings

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

19 of 23 people (83%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I tokenize a string using more than 1 separator?

Jul 8th, 2000 18:45
unknown unknown, Mikael Olofsson


use re.split:

>>> import re
>>> s = "one,two;three:four,five;six:seven"
>>> re.split("[,;:]", s)
['one', 'two', 'three', 'four', 'five', 'six', 'seven']
>>> sep = re.compile("[,;:]")
>>> sep.split(s)
['one', 'two', 'three', 'four', 'five', 'six', 'seven']

---- Alternately ----

seps = ':|/'
mystring = 'foo:bar|baz/zot'
newstring = string.join(map(lambda x, seps=seps:(x+seps[0])[x in 
seps],a),'')
result = string.split(newstring,seps[0])