regex解决方案(对我来说)似乎非常简单:import re
def split_string(source,separators):
return re.split('[{0}]'.format(re.escape(separators)),source)
示例:
^{pr2}$
在这里使用regex的原因是如果您不想在分隔符中使用' ',这仍然有效。。。在
另一种选择(我想我更喜欢),您可以使用多字符分隔符:def split_string(source,separators):
return re.split('|'.join(re.escape(x) for x in separators),source)
在这种情况下,多字符分隔符作为某种非字符串iterable(例如元组或列表)传入,但单字符分隔符仍然可以作为单个字符串传入。在>>> 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']
或者,最后,如果您还想在连续的分隔符上拆分:def split_string(source,separators):
return re.split('(?:'+'|'.join(re.escape(x) for x in separators)+')+',source)
它给出了:>>> split_string("Before the rain ... there was lightning and thunder.", " .")
['Before', 'the', 'rain', 'there', 'was', 'lightning', 'and', 'thunder', '']