The regex solution (to me) seems like it would be pretty easy:
import re
def split_string(source,separators):
return re.split('[{0}]'.format(re.escape(separators)),source)
example:
>>> import re
>>> def split_string(source,separators):
... return re.split('[{0}]'.format(re.escape(separators)),source)
...
>>> split_string("the;foo: went to the store",':;')
['the', 'foo', ' went to the store']
The reason for using a regex here is in the event that you don't want to have ' ' in your separators, this will still work ...
An alternative (which I think I prefer), where you could have multi-character separators is:
def split_string(source,separators):
return re.split('|'.join(re.escape(x) for x in separators),source)
In this case, the multi-character separators things get passed in as some sort of non-string iterable (e.g. a tuple or a list), but single character separators can still be passed in as a single string.
>>> def split_string(source,separators):
... return re.split('|'.join(re.escape(x) for x in separators),source)
...
>>> split_string("the;foo: went to the store",':;')
['the', 'foo', ' went to the store']
>>> split_string("the;foo: went to the store",['foo','st'])
['the;', ': went to the ', 'ore']
Or, finally, if you want to split on consecutive runs of separators as well:
def split_string(source,separators):
return re.split('(?:'+'|'.join(re.escape(x) for x in separators)+')+',source)
which gives:
>>> split_string("Before the rain ... there was lightning and thunder.", " .")
['Before', 'the', 'rain', 'there', 'was', 'lightning', 'and', 'thunder', '']
.splittakes a regular expression in python; why can't you usesource.split(separators)? What isseparatorsexactly? (like an example)str.split()doesn't take a regex, it just takes a string - (if you want a regex, that'sre.split())..replacetakes a selection of characters...