Skip to content Skip to sidebar Skip to footer

Using Python To Split Long String, By Given ‘separators’

Environment: Win 7; Python 2.76 I want to split a long string into pieces, according to given separator The string looks like: “C-603WallWizard45256CCCylinders:2HorizontalOpposed

Solution 1:

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)

Post a Comment for "Using Python To Split Long String, By Given ‘separators’"