'Finding the index of a common character in a for loop

First of all I know this is probably a [duplicate] but I could not find the answer to my question specifically anywhere.

I have a string generated by the user that I want my program to iterate over. Everything goes fine except for the fact that because I'm trying to access the index of a character " " (space) which appears more than once, whenever I try getting the index of the newly assigned space value for " ", it automatically gives me the index of the first " " in the string. I want this program to differentiate between words and create a list with the words in the string using a space to distinguish between them. What am I doing wrong?

list_words=[]
def findwords(sentence):
    index1=0
    index2=0
    for space in sentence:
        if space==" ":
            index1=sentence.index(space)
            list_words.append(sentence[index2:index1])
            index2=index1  
    print(list_words)
findwords("What is your name?")


Solution 1:[1]

If you want a list of words, then use the API that was designed for that purpose:

def findwords(sentence):
    return sentence.split()
print(findwords("What is your name?"))

Solution 2:[2]

As @Tim Roberts mentioned, you can simply use sentence.split(" ") to retrieve a list of words in the sentence split by a space. This function creates a list that has elements as words of the sentence that are divided by a " ".

However, using your code, we can edit it so that after we find a space, we add the previous word to the list and we edit sentence so that it does not contain the previous word or space. After we reach the end of the sentence, since there is no space ending the sentence, after the for loop, we should add whatever word is left in our sentence to the list.

Remember to use a copy of sentence to iterate as we should not modify whatever we are iterating. This code is built off of your code and produces the same output as using sentence.split(" "):

list_words=[]
def findwords(sentence):
    sent = sentence
    for space in sent:
        if space == " ":
            index1=sentence.index(space)
            list_words.append(sentence[0:index1 + 1])
            sentence = sentence[index1 + 1:]
    list_words.append(sentence)
findwords("What is your name?")
print(list_words)

Output:

['What ', 'is ', 'your ', 'name?']

I hope this helped answer your question! Let me know if you need any further details or clarification :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Roberts
Solution 2 Ani M