How to find all indices of a certain character in a list or string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

How to find all indices of a certain character in a list or string

For example we have: alpha = ['a', 'b', 'a', 'c', 'a'] Or beta = 'abaca' How can I find all indices of 'a' in alpha and beta? Is defining a function the only way?

16th Sep 2020, 11:40 AM
pedram ch
pedram ch - avatar
5 Answers
+ 8
This is a comprehension that can do this taks: string = 'hello world' char = 'o' print([v for v, x in enumerate(string) if x == char]) # result is: [4, 7]
16th Sep 2020, 12:22 PM
Lothar
Lothar - avatar
+ 4
Jan Markus yess thank you so much I guess I should review regular expressions 😅
16th Sep 2020, 11:59 AM
pedram ch
pedram ch - avatar
+ 4
Steven M thank you very much🙏, pandas seems like a very useful package I should start learning it soon
16th Sep 2020, 12:00 PM
pedram ch
pedram ch - avatar
+ 3
Could try Pandas? import pandas as pd lst=['a','b','a','b','a','b','b','b','a'] df=pd.DataFrame(lst) print(list(df[df[0]=='a'].index))
16th Sep 2020, 11:56 AM
Steven M
Steven M - avatar
+ 3
Lothar that is a cool method I was also looking for a build in method to this task thank you so much
16th Sep 2020, 12:39 PM
pedram ch
pedram ch - avatar