1

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?

  • 1
    In your second example, you don't have `index` variable defined before you call index method on `sentence` – gajendragarg Mar 21 '22 at 11:54
  • This [Post](https://stackoverflow.com/questions/11122291/how-to-find-char-in-string-and-get-all-the-indexes) should fit your issue. – cytings Mar 21 '22 at 11:56
  • call the instruction several times. each time it will use the previous index as the starting one, so it will find the next i –  Mar 21 '22 at 11:56
  • @gajendragarg oh I see not but it only comes out as 7 and not 3 7 also with find it only prints the first one and not the second one – I_Hate_Xcode Mar 21 '22 at 11:56
  • @I_Hate_Xcode The `index()` method finds the first occurrence of the specified value. So after you increase the index value by 1. It will search for `i` from index 4 of string to end – gajendragarg Mar 21 '22 at 11:58
  • 2
    Does this answer your question? [How to find all the indexes of a recurring item in a list?](https://stackoverflow.com/questions/46701978/how-to-find-all-the-indexes-of-a-recurring-item-in-a-list) – Devang Sanghani Mar 21 '22 at 11:58
  • @gajendragarg I want it to find i from index 3 to end how do I do that? – I_Hate_Xcode Mar 21 '22 at 12:02

1 Answers1

0

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]
constantstranger
  • 9,176
  • 2
  • 5
  • 19