Wednesday, January 4, 2012

Split String Multiple Delimiters Python

The python function split([sep,[,maxsplit]]) is a good way to split a string for a given delimiter or sep. The delimiter may itself be composed of multiple characters. However, this function is insufficient when multiple delimiters are considered.

>>> l = "Birds;and,Bees"
>>> l.split(";,")
['Birds;and,Bees']

The way to achieve this is to use the regular expression package and use the re.split(pattern, string, maxsplit=0, flags=0) method available from the package.


>>> import re
>>> re.split(";|,",l)
['Birds', 'and', 'Bees']


The key is to use the "|" operator to indicate multiple delimiters.

1 comment: