嗨,我真的很困惑这一点,我很难做出“我们已经完成”的部分。只有在我运行代码时,结果才会是['Hooray', ' Finally']
def split_on_separators(original, separators):
""" (str, str) -> list of str
Return a list of non-empty, non-blank strings from the original string
determined by splitting the string 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."]
"""
#I can't make we're done .
result = []
string=''
for ch in original:
if ch in separators:
result.append(string)
string=''
if '' in result:
result.remove('')
else:
string+char
return result
答案 0 :(得分:1)
这一行:
string+char
正在计算某些东西,但没有分配它。
请改为尝试:
string=string+char
或者,您可以缩短它以使用+=
简写:
string += char
与上述内容相同。
答案 1 :(得分:1)
def split_on_separators(original, separators):
result = []
string=''
for index,ch in enumerate(original):
if ch in separators or index==len(original) -1:
result.append(string)
string=''
if '' in result:
result.remove('')
else:
string = string+ch
return result
res = split_on_separators("Hooray! Finally, we're done.", "!,")
print(res)
在您的解决方案中,您只测试分隔符。因此,当字符串终止时,没有任何反应,并且不添加最后一个字符串。您还需要测试字符串终止。
请注意,您没有将当前字符附加到字符串,因此最后一个字符串有一个“。”。也许这就是你想要的(看起来像我的分隔符;))