Home > other >  I can't find a letter more than 1 using index
I can't find a letter more than 1 using index

Time:03-21

I was playing with index and did finding letter's place

sentence = "Coding is hard"

index = sentence.index("i")
print(index)

worked fine for me, however when I wanted to find more than just 1 i it didn't work?

sentence = "Coding is hard"

index = sentence.index("i", index   1) 
print(index)

it doesn't work? can somebody explain please?

CodePudding user response:

While index() is one approach, and commenters have given you pointers to help with that, another way to find all occurrences of a character in a string is to use a list comprehension:

sentence = "Coding is hard"
indices = [i for i, c in enumerate(sentence) if c == "i"]
print(indices)

This prints:

[3, 7]
  • Related