+ 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?
5 Réponses
+ 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]
+ 4
Jan Markus yess thank you so much I guess I should review regular expressions 😅
+ 4
Steven M thank you very much🙏, pandas seems like a very useful package I should start learning it soon
+ 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))
+ 3
Lothar that is a cool method I was also looking for a build in method to this task thank you so much