python - 在字符串中查找char - 我可以获取所有索引吗?

Wil*_*ing 46 python string

我得到了一些简单的代码:

def find(str, ch):
    for ltr in str:
        if ltr == ch:
            return str.index(ltr)
find("ooottat", "o")
Run Code Online (Sandbox Code Playgroud)

该函数仅返回第一个索引.如果我改变返回打印,它将打印0 0 0.为什么这是有没有办法得到0 1 2

Lev*_*sky 81

这是因为str.index(ch)将返回ch第一次出现的索引.尝试:

def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]
Run Code Online (Sandbox Code Playgroud)

这将返回您需要的所有索引的列表.

PS Hugh的答案显示了一个生成器函数(如果索引列表变大,它会有所不同).此功能也可以通过更改[]为来调整().

  • @ChrisNielsen 确实,这不适用于更长的子字符串,因为`enumerate` 迭代`s` 中的字符,因此如果`ch` 是单个字符,则`ltr == ch` 只能是`True`。 (2认同)

Jon*_*nts 17

我会和Lev一起去,但值得指出的是,如果你最终得到更复杂的搜索,那么使用re.finditer可能值得记住(但是经常会造成更多麻烦而不是值得 - 但有时候也很方便了解)

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)]
Run Code Online (Sandbox Code Playgroud)


Hug*_*ell 10

def find_offsets(haystack, needle):
    """
    Find the start of all (possibly-overlapping) instances of needle in haystack
    """
    offs = -1
    while True:
        offs = haystack.find(needle, offs+1)
        if offs == -1:
            break
        else:
            yield offs

for offs in find_offsets("ooottat", "o"):
    print offs
Run Code Online (Sandbox Code Playgroud)

结果是

0
1
2
Run Code Online (Sandbox Code Playgroud)


Mar*_*som 9

Lev的答案是我使用的答案,但是这里的内容基于您的原始代码:

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

>>> list(find("ooottat", "o"))
[0, 1, 2]
Run Code Online (Sandbox Code Playgroud)