给定字符串“the dude is a cool dude”,
我想找到“花花公子”的第一个索引:
mystring.findfirstindex('dude') # should return 4
这个的python命令是什么?
原文由 Shai UI 发布,翻译遵循 CC BY-SA 4.0 许可协议
给定字符串“the dude is a cool dude”,
我想找到“花花公子”的第一个索引:
mystring.findfirstindex('dude') # should return 4
这个的python命令是什么?
原文由 Shai UI 发布,翻译遵循 CC BY-SA 4.0 许可协议
index
和 find
在 find
方法旁边还有 index
。 find
and index
both yield the same result: returning the position of the first occurrence, but if nothing is found index
will raise a ValueError
而 find
返回 -1
。速度方面,两者具有相同的基准测试结果。
s.find(t) #returns: -1, or index where t starts in s
s.index(t) #returns: Same as find, but raises ValueError if t is not in s
rfind
和 rindex
:通常,find 和 index 返回传入字符串开始处的最小索引,而
rfind
和rindex
返回其开始处的最大索引 大多数字符串搜索算法从 左侧 搜索 向右,因此以r
开头的函数表示搜索是 从右到左进行的。
因此,如果您正在搜索的元素的可能性接近列表的末尾而不是列表的开头, rfind
或 rindex
会更快。
s.rfind(t) #returns: Same as find, but searched right to left
s.rindex(t) #returns: Same as index, but searches right to left
资料来源: Python:视觉快速入门指南,Toby Donaldson
原文由 user1767754 发布,翻译遵循 CC BY-SA 3.0 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答879 阅读✓ 已解决
1 回答1.8k 阅读✓ 已解决
find()