When using .index in a list only returns first time it appears in the array

前端 未结 2 1345
[愿得一人]
[愿得一人] 2021-01-23 16:12
sentence = \"ask not what your country can do for you ask what you can do for your country\"
sentList = sentence.split()

print(sentence)
userWord = input(\"Pick a word          


        
2条回答
  •  情书的邮戳
    2021-01-23 16:27

    list.index accepts additional start index (and end index). Pass the index to find next matched item index.

    ...
    
    if userWord in sentList:
        i = 0
        while True:
            try:
                i = sentList.index(userWord, i)  # <---
            except ValueError:  # will raise ValueError unless the item is found
                break
            i += 1
            print("{} appears in the sentence in the {}th position".format(
                userWord, i
            ))
    
    else:
         ....
    

提交回复
热议问题