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
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)
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)
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
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)
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)