Splits strings with multiple separators instead of one (e.g.
Python, 14 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14
def tsplit(string, delimiters): """Behaves str.split but supports multiple delimiters.""" delimiters = tuple(delimiters) stack = [string,] for delimiter in delimiters: for i, substring in enumerate(stack): substack = substring.split(delimiter) stack.pop(i) for j, _substring in enumerate(substack): stack.insert(i+j, _substring) return stack
Many times I've wanted to split a string with multiple separators.
>>> s = 'thing1,thing2/thing3-thing4' >>> tsplit(s, (',', '/', '-')) ['thing1', 'thing2', 'thing3', 'thing4']
Tags: split, string, string_parsing
How about this:
This version allows for a more flexible separator which can be a string, tuple, or list.
@sunjay, I like that, but sometimes you want to split by more than one character at a time.
re.split() is simpler:
or just use re.split() directly:
@Kent in re.split you have to escape special regexp characters like . \ *
@Denis - Yes, that is what
map(re.escape, delimiters)does in my tsplit() function. Of course if you are calling re.split() directly you have to give a correct regex yourself.
@Johnson - Thanks for the four line solution that uses