Skip to content

Instantly share code, notes, and snippets.

@kennethreitz
Created March 20, 2011 20:36
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kennethreitz/878652 to your computer and use it in GitHub Desktop.
Save kennethreitz/878652 to your computer and use it in GitHub Desktop.
Split Strings w/ Multiple Separators (Python)
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
>>> s = 'thing1,thing2/thing3-thing4'
>>> tsplit(s, (',', '/', '-'))
['thing1', 'thing2', 'thing3', 'thing4']
@kennethreitz
Copy link
Author

I might try to get this into the standard lib. I see no reason for it to not be included.

@mrtazz
Copy link

mrtazz commented Mar 21, 2011

Nice. Very useful. I also tried to create a less loop-y version in a fork.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment