Created
March 20, 2011 20:36
-
-
Save kennethreitz/878652 to your computer and use it in GitHub Desktop.
Split Strings w/ Multiple Separators (Python)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> s = 'thing1,thing2/thing3-thing4' | |
>>> tsplit(s, (',', '/', '-')) | |
['thing1', 'thing2', 'thing3', 'thing4'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. Very useful. I also tried to create a less loop-y version in a fork.