basic question about finding all indices of an occurrences in a string

Question:

i am in the first weeks of learning how to code in python and i need some feedback on a simple piece of code I have written

Objective: find and print all indices of “e” in a string

the code i have written

sentence = "celebrate"

for i in sentence:
    if i == "e":
        indexed_sentence = sentence.index("e")
        print(indexed_sentence)

I would like the code to print
1,3,8

Asked By: Eelco

||

Answers:

The .index method will return the index of the first occurrence of the character(s) you are searching for. This means you will always see 1 for your code. A better method is to use the built-in function enumerate as @Rakesh suggested.

sentence = "celebrate"

for ix, c in enumerate(sentence):
    if c=="e":
        print(ix)
Answered By: James

You are looping over the string and matching the character you want correctly. When you found the match, you are just running indexed_sentence = sentence.index("e") which would give same answer everytime. You can modify your loop so that you know the index of the match as well using enumerate.

sentence = "celebrate"

for i, c in enumerate(sentence):
    if c == "e":
        print(i)

Answered By: Shashank V
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.