Home > Back-end >  Using Python's Find() in a while loop to return the index of words in a string
Using Python's Find() in a while loop to return the index of words in a string

Time:05-09

A problem I'm working on involves using a while loop to iterate through a string, using the Find() function to return the index of a specific word in that string whenever it appears. For this example it's finding the name 'Weena' in a string variable containing the entirety of The Time Machine. I am being asked to specifically use while loops and the Find() function, though I've already solved the problem using an enumerator.

for count, word in enumerate(time_machine_text.split()):
    if 'Weena' in word:
        print(count)

I'm used to foreach loops because I relied on them a lot when I was learning C#, so every looping problem I see I just default to foreach loops. Any advice to meet the task's requirements of using a while loop and the Find() function would be much appreciated.

CodePudding user response:

I would just intialize count variable separately and use while loop to iterate through time_machine_text.split(). For example:

count = 0
words = time_machine_text.split()
while count < len(words):
    word = words[count]
    if "weena" in word:
        print(count)
    count  = 1

Edit: This is the version using find() function

count = 0
words = time_machine_text.split()
while count < len(words):
    word = words[count]
    if word.find("weena") != -1:
        print(count)
    count  = 1
  • Related