Home > database >  Python turning characters from a string into words into list items
Python turning characters from a string into words into list items

Time:08-01

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

CodePudding user response:

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])
  • Related