0

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 
asked Mar 7, 2014 at 4:45

2 Answers 2

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)

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 ;) )

answered Mar 7, 2014 at 5:05
Sign up to request clarification or add additional context in comments.

2 Comments

it actually only returned the [] when i applied what you did...but what you did is more reasonable but i don't know why it returned this
@user3283844 no it does not return []. Check my code, there is a line which does string = string +ch. You only had string+ch, if you have it like that it returns []
1

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.

answered Mar 7, 2014 at 4:50

3 Comments

well..i did this but it didn't work. i just can't know how to assign the we're done
Well, your code is different to the one you put in the question. The only issue I can immediately see is you don't assign anything.
there's even a bug as user3283844 has string+char, which doesn't even compile. it's string = string+ch ;)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.