开发者

Finding index of the same elements in a list

开发者 https://www.devze.com 2023-04-10 14:47 出处:网络
Suppose I have to find each index of letter \'e\' in the word \"internet\": letter = \'e\' word = \'interne开发者_StackOverflow社区t\'

Suppose I have to find each index of letter 'e' in the word "internet":

letter = 'e'
word = 'interne开发者_StackOverflow社区t'
idx = word.index(letter)

But this code gives only the first index. How can I find the rest of them?


Try using enumerate in a list comprehension:

[index for (index, letter) in enumerate(word) if letter == 'e']


Mark's answer is better for a single letter. I'm adding this in case your real substring is longer than a single character.

If you want to use str.index(), it can take an optional start position and will raise a ValueError if the desired substring is not found:

>>> letter = 'e'
>>> word = 'internet'
>>> last_index = -1
>>> while True:
...     try:
...         last_index = word.index(letter, last_index + 1)
...         print last_index
...     except ValueError:
...         break
... 
3
6


Try this:

word = 'internet'
letter = 'e'
[i for i in xrange(len(word)) if word[i] == letter]
0

精彩评论

暂无评论...
验证码 换一张
取 消