character of python - find char in string - can I get all indexes?




3 Answers

I would go with Lev, but it's worth pointing out that if you end up with more complex searches that using re.finditer may be worth bearing in mind (but re's often cause more trouble than worth - but sometimes handy to know)

test = "ooottat"
[ (i.start(), i.end()) for i in re.finditer('o', test)]
# [(0, 1), (1, 2), (2, 3)]

[ (i.start(), i.end()) for i in re.finditer('o+', test)]
# [(0, 3)]
python find character in string

I got some simple code:

def find(str, ch):
    for ltr in str:
        if ltr == ch:
            return str.index(ltr)
find("ooottat", "o")

The function only return the first index. If I change return to print, it will print 0 0 0. Why is this and is there any way to get 0 1 2?




Lev's answer is the one I'd use, however here's something based on your original code:

def find(str, ch):
    for i, ltr in enumerate(str):
        if ltr == ch:
            yield i

>>> list(find("ooottat", "o"))
[0, 1, 2]



Using pandas we can do this and return a dict with all indices, simple version:

import pandas as pd

d = (pd.Series(l)
     .reset_index()
     .groupby(0)['index']
     .apply(list)
     .to_dict())

But we can build in conditions too, e.g. only if two or more occurences:

d = (pd.Series(l)
     .reset_index()
     .groupby(0)['index']
     .apply(lambda x: list(x) if len(list(x)) > 1 else None)
     .dropna()
     .to_dict())





Related