0

I have a fairly simple question that I just can't seem to figure out. How would one find what I'm asking for in the title in Python 2.7? Let me explain better:

Say you have a string:

string = "banana"

I know how you would find the position of a letter if it appears once in a string, for example:

string.find("b")

would return 0.

Now if I wanted to find all of the places a letter appears if it appears more than once in the string, I have a problem. For example:

string.find("a")

would return 1, however, it also appears in slots 3 and 4 too.

What I'm asking is how would I be able to determine which slots a letter appears in a string, even if it appears more than once? Thanks for your time.

user163505
  • 481
  • 3
  • 11
  • 22

1 Answers1

3

If you use a list comprehension and enumerate, you can get a list of the indexes at which a certain character appears:

>>> string = "banana"
>>>
>>> list(enumerate(string))  # Just to demonstrate
[(0, 'b'), (1, 'a'), (2, 'n'), (3, 'a'), (4, 'n'), (5, 'a')]
>>>
>>> [x for x,y in enumerate(string) if y == 'a']
[1, 3, 5]
>>> [x for x,y in enumerate(string) if y == 'n']
[2, 4]
>>>