'I can't find a letter more than 1 using index
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?
Solution 1:[1]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | constantstranger |
