[Solved] Using Python to split long string, by given ‘separators’ [duplicate]


If you want to split by any instance of any of those separators, you may want a regular expression:

r = re.compile(r'|'.join(separators))
r.split(s)

Note that this is not a safe way to build regexps in general; it only works here because I know that none of your separators contain any special characters. If you don’t know that for sure, use re.escape:

r = re.compile(r'|'.join(map(re.escape, separators)))

If you want to split by those separators exactly once each, in exactly that order, you probably want to use either str.split or str.partition:

bits = []
for separator in separators:
    first, _, s = s.partition(separator)
    bits.append(first)
bits.append(s)

1

solved Using Python to split long string, by given ‘separators’ [duplicate]