How to find the indexes of all occerences of a character in a string? [duplicate]

一个人想着一个人 提交于 2019-12-20 04:28:13

问题


I guess the heading is self-explanatory, still, I'll make myself more clear.

I've to find the indexes of every occurrence of a character in a string. For example,

word = "banana"
def indexes(x, word):
    #some code
    return (list of indexes of x character in the word)

output:

indexes('a', word)
>> [1, 3, 5]

How do I get this result?


回答1:


Try this:

word = "banana"
def indexes(x, word):
    output = []
    for i,y in enumerate(word):
        if x == y:
            output.append(i)
    return output

output = indexes("a", word)
print(output)



回答2:


Using list comprehension

  • enumerate() - method adds a counter to an iterable and returns it in a form of enumerate object.

Ex.

word = "banana"
indexes = [ index for index,x in enumerate(word) if x in 'a' ]
print(indexes)

O/P:

[1, 3, 5]



回答3:


i would do something like this

word = "banana"
def indexes(x, word):
  result = []
  for idx, letter in enumerate(word):
    if letter == x:
      result.append(idx)
  return result

and then

indexes('a', word)
[1, 3, 5]


来源:https://stackoverflow.com/questions/57309688/how-to-find-the-indexes-of-all-occerences-of-a-character-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!