2

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

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Eelco
  • 49
  • 1
  • 3

2 Answers2

1

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)
James
  • 32,991
  • 4
  • 47
  • 70
1

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)

Shashank V
  • 10,007
  • 2
  • 25
  • 41