I would like to find all the indexes of the letter 'a' in a string 'akacja'. However python always seems to return only the first index that it has found. Any solutions? Thanks for help.
Asked
Active
Viewed 649 times
-1
-
Welcome to Stack Overflow! Please read the [tour], and maybe browse the [Help]. When asking about code that you cannot get to work, include that code in your question so we can tell you where you went wrong. If the full code is too long, condense it into a [mcve]. – Jongware Dec 09 '18 at 22:13
2 Answers
0
You could use list comprehension since str.index()
and str.find()
will only return the first index:
s = 'akacja'
indexes = [i for i, c in enumerate(s) if c == 'a']
print(indexes)
# OUTPUT
# [0, 2, 5]

benvc
- 14,448
- 4
- 33
- 54
0
You could do this …
indexes = [i for i,c in enumerate('akacja') if c == 'a']
The above line uses list comprehension which is short hand for:
indexes = []
for i,c in enumerated('akacja'):
if c == 'a':
indexes.append(i)
You could also use regex like so:
import re
indexes = [f.start() for f in re.finditer('a', 'akacja')]

Red Cricket
- 9,762
- 21
- 81
- 166