Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python turning characters from a string into words into list items

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading