如何在字符串中查找字符并获取所有索引? [英] How to find char in string and get all the indexes?
本文介绍了如何在字符串中查找字符并获取所有索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到了一些简单的代码:
I got some simple code:
def find(str, ch):
for ltr in str:
if ltr == ch:
return str.index(ltr)
find("ooottat", "o")
该函数只返回第一个索引.如果我改变返回打印,它会打印 0 0 0.为什么会这样,有什么办法可以得到 0 1 2
?
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
?
推荐答案
这是因为 str.index(ch)
将返回 ch
第一次出现的索引.试试:
This is because str.index(ch)
will return the index where ch
occurs the first time. Try:
def find(s, ch):
return [i for i, ltr in enumerate(s) if ltr == ch]
这将返回您需要的所有索引的列表.
This will return a list of all indexes you need.
附言Hugh 的回答显示了一个生成器函数(如果索引列表变大会有所不同).这个函数也可以通过将[]
改为()
来调整.
P.S. Hugh's answer shows a generator function (it makes a difference if the list of indexes can get large). This function can also be adjusted by changing []
to ()
.
这篇关于如何在字符串中查找字符并获取所有索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文