0

So I have this assignment for a class where I have to split user input text into words and then into list items.(we are not allowed to use the inbuilt split function) I came up with a solution that just goes through every character and combines them if there isn't a space in between.

def my_split(sentence,seperator):
    list = []
    newStr = ""
    for i in range(len(sentence)):
        if sentence[i].isalpha():
            newStr += sentence[i]
        else:
            list.append(newStr+seperator)
            newStr = ""
    print(list)

def main():
    while True:
        anws = input("Write the sentence:")
        my_split(anws,",")

        break
if __name__ == "__main__":
    main()

The code almost works, except it always leaves the last word out for some reason. How can I fix that?

Image of output

EDIT: Lots of comments about the seperator...I misunderstood that part of the assignment :D it's supposed to point out what we are looking for between the words(the space).

  • 3
    Have you tried to run a small example manually on paper (or code editor), and see what happens when you run through your code? Try with "last word out" as input. – spac Jul 31 '22 at 18:24
  • Your issue is in `if` `else` block as you are appending new item only if it's not alpha so that's the reason last word is being skipped. And what if an number is present in the string. It would lead to another bug. – GodWin1100 Jul 31 '22 at 18:24
  • `list` is a keyword in python and it can cause problems when you use it as a variable name. I suggest you call that list something else. That isn't why your code isn't working, however. – scatter Jul 31 '22 at 18:25
  • add `list.append(newStr+separator)` below your `for` loop to add the last word and check with `isalnum()` to consider numbers also. It could solve current issue. – GodWin1100 Jul 31 '22 at 18:30
  • It seems curious that you are adding the separator (in your example code you are using a comma) to each output string. Is that one of the things the assignment said to do? – skumhest Jul 31 '22 at 18:32
  • I would not add the sepArator at the above stage, if you reassemble then that would be a more appropriate time. I would be inclined to split at white space. Also, you might want to check that newStr is not empty before adding to the list. – copper.hat Jul 31 '22 at 18:37

1 Answers1

0

What's wrong with your code:

    for i in range(len(sentence)):
        # Your issue is that here if the last char is a letter [a-zA-Z]
        # It will only add to newStr variable, and not append to the [list] that is what actually shows the match results
        if sentence[i].isalpha():
            newStr += sentence[i]
        else:
            list.append(newStr+seperator)
            newStr = ""

You should include the last newStr together with the list variable because it will include the last out word even if there's no comma at end, but it should be done only if newStr is not empty cause it indicates there's a word at end that was not included before.

def my_split(sentence, seperator):
    list = []
    newStr = ""
    for i in range(len(sentence)):
        if sentence[i].isalpha():
            newStr += sentence[i]
        else:
            list.append(newStr+seperator)
            newStr = ""
    # Create a new list only if newStr is not empty
    last_word = [newStr] if newStr else []
    # Concatenate both lists (your results and the last word if any)
    print([*list, *last_word])
Alex Rintt
  • 1,618
  • 1
  • 11
  • 18
  • 1
    In analyzing this question, I came up with pretty much the same logic. The only thing I would add is that I don't see the need for the separator constant in your function. Currently with it you would get a list like ['Hello,', 'from,', 'Earth,'] if the sentence was "Hello from Earth". If you remove the separator from your function and function call, you should get ['Hello', 'from', 'Earth'] which is more customary for a list. Something to think about. – NoDakker Jul 31 '22 at 18:39
  • Agree and you're right, probably he will need to remove the comma, but the question is: "The code almost works, _except_ it always leaves the last word out for some reason. How can I fix that?" So I'm just answering what he asked for. – Alex Rintt Jul 31 '22 at 18:42
  • That definetly fixed it. Thanks a lot! – Avaruusolento Jul 31 '22 at 18:49
  • Why do you create a (possibly empty) list for the last word? I would simply do `if newStr: lst.append(newStr). Also, I would you the same syntax for the `append` in the loop, just in case the input contains two or more consecutive spaces – gimix Jul 31 '22 at 18:49
  • @Avaruusolento, the situation you met here is very common and you will find it in many, many use cases - so try to always keep the solution in mind :) – gimix Jul 31 '22 at 18:53
  • I'm most used to declarative ways of programming, so I avoid (not because is bad but because I'm not used to) writing something like `list.doIt` or `something.setIt`. Take a look at declarative vs imperative https://stackoverflow.com/questions/1784664/what-is-the-difference-between-declarative-and-imperative-paradigm-in-programmin – Alex Rintt Jul 31 '22 at 19:01