python 写一个 split_on_separator

问题如下
def split_on_separators(original, separators):
""" (str, str) -> list of str

Return a list of non-empty, non-blank strings from original,
determined by splitting original on any of the separators.
separators is a string of single-character separators.

>>> split_on_separators("Hooray! Finally, we're done.", "!,")
['Hooray', ' Finally', " we're done."]

我写的是
result = [original]
for i in separators:
original = original.replace(i, '>>.<')
result = original.split('>>.<')
for word in result:
if word == '':
result.remove(word)
return result

可是我试了 "this is the first sentence. Isn't it? Yes ! !! This" 的话得到答案里有很多符号, 不知道怎么改

# coding:utf8
def split_on_separators(original, separators):
result=[]
for i in separators:
if len(result) == 0: # 第一次分割
result=original.split(i)
else:
for index,word in enumerate(result): # 既要遍历索引又要遍历元素,前面是index,后面是值value
if i in word:
result=result[:index]+word.split(i)+result[index:] # 拼接
print result # 测试过后加上注释
result.remove(word) # 剔除
print result # 测试过后加上注释
# return result # 测试过后去掉注释

split_on_separators("Hooray! Finally, we're done.", "!,")

测试结果:
['Hooray', " Finally, we're done."]
['Hooray', ' Finally', " we're done.", " Finally, we're done."]
['Hooray', ' Finally', " we're done."]
[Finished in 0.1s]
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-07
你可以用正则表达式;追问

不能从我有的基础改吗?

追答

你这是替换掉了原来里面的“i”??

相似回答