Hi I am really confused in this one, it is very hard for me to make the part 'we're done'. Only when I run the code, the result would only be ['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
2 Answers 2
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)
In your solution, you only test for separators. So when the string is terminated, nothing happens and the last string is not added. You need to test for string termination as well.
Please also take note that you are not appending the current character to the string, so the last string has a ".". Maybe it's what you want (looks like a separator to me ;) )
2 Comments
This line:
string+char
is computing something, but not assigning it.
Try this instead:
string=string+char
Or, you can shorten it to use += shorthand:
string += char
Which is equivilent to the above.