Skip to content Skip to sidebar Skip to footer

Is It Possible To Split A String On Multiple Delimiters In Order?

I know how to split a string based on multiple separators using re as in this question: Split Strings with Multiple Delimiters?. But I'm wondering how to split a string using the o

Solution 1:

If I understand what you're asking, you just want a series of string partition operations: first partition on the first separator, then the second, etc to the end.

Here's a recursive method (which doesn't use re):

def splits(s,seps):
    l,_,r = s.partition(seps[0])
    iflen(seps)== 1:
        return [l,r]
    return [l] + splits(r,seps[1:])

demo:

a ='hello^goo^dbye:cat@dog'

splits(a,['^',':','@'])
Out[7]: ['hello', 'goo^dbye', 'cat', 'dog']

Solution 2:

I believe your question is severely under-specified, but at least this gives the result you want in the example you gave:

def split_at_most_once_each_and_in_order(s, seps):
    result= []
    start=0for sep in seps:
        i = s.find(sep, start)
        if i >=0:
            result.append(s[start: i])
            start= i+1
    if start< len(s):
        result.append(s[start:])
    returnresult

print split_at_most_once_each_and_in_order(
    "hello^goo^dbye:cat@dog", "^:@")

That returns ['hello', 'goo^dbye', 'cat', 'dog']. If you absolutely want to "be clever", keep looking ;-)

Post a Comment for "Is It Possible To Split A String On Multiple Delimiters In Order?"