Last active
March 15, 2017 01:37
-
-
Save DavidAntliff/bcc97d6f649123b6d61f298a666b2744 to your computer and use it in GitHub Desktop.
Python: partition a string with a set of delimiters
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
import re | |
def partition(string, delimiters): | |
"""Split a string into a (head, sep, tail) tuple based on the | |
first occurrence of a delimiter in the string. | |
This is similar to str.partition() except it accepts a set of delimiters. | |
The set can be a list/tuple of characters, or a string.""" | |
seps = "".join(delimiters) | |
return re.match(r"([^{seps}]*)([{seps}]?)(.*)".format(seps=seps), string).groups() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment