1

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?

Parthik B.
  • 472
  • 1
  • 5
  • 15

3 Answers3

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]
bharatk
  • 4,202
  • 5
  • 16
  • 30
2

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)
Nouman
  • 6,947
  • 7
  • 32
  • 60
  • Thank you very much to help me. Your code surely works. But I've to mark the other guy's solution green as he answered first. Again, thank you. – Parthik B. Aug 01 '19 at 13:13
1

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]
Cyril Gratecos
  • 291
  • 2
  • 6