如何找到 python 字符串中第一次出现的子字符串?

新手上路,请多包涵

给定字符串“the dude is a cool dude”,

我想找到“花花公子”的第一个索引:

 mystring.findfirstindex('dude') # should return 4

这个的python命令是什么?

原文由 Shai UI 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 260
2 个回答

find()

 >>> s = "the dude is a cool dude"
>>> s.find('dude')
4

原文由 mechanical_meat 发布,翻译遵循 CC BY-SA 2.5 许可协议

快速概览: indexfind

find 方法旁边还有 indexfind and index both yield the same result: returning the position of the first occurrence, but if nothing is found index will raise a ValueErrorfind 返回 -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

附加知识: rfindrindex

通常,find 和 index 返回传入字符串开始处的最小索引,而 rfindrindex 返回其开始处的最大索引 大多数字符串搜索算法从 左侧 搜索 向右,因此以 r 开头的函数表示搜索是 从右到左进行的

因此,如果您正在搜索的元素的可能性接近列表的末尾而不是列表的开头, rfindrindex 会更快。

 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题