如何在 python 字符串中找到子字符串的第一个匹配项?

根据字符串“这家伙是个很酷的家伙”
我想找到“花花公子”的第一个索引:

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

这个命令的 python 命令是什么?

263581 次浏览

find()

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

快速概述: indexfind

find方法旁边还有 indexfindindex都产生相同的结果: 返回第一次出现的位置,如果没有发现 index但是将产生 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

附加知识: 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: Visual QuickStart Guide,Toby Donaldson

通过不使用任何 Python 内置函数,以算法的方式实现这一点。 这可以实现为

def find_pos(string,word):


for i in range(len(string) - len(word)+1):
if string[i:i+len(word)] == word:
return i
return 'Not Found'


string = "the dude is a cool dude"
word = 'dude'
print(find_pos(string,word))
# output 4
def find_pos(chaine,x):


for i in range(len(chaine)):
if chaine[i] ==x :
return 'yes',i
return 'no'

当所有人都在怀疑你的时候,如果你能保持冷静,如果你能相信自己,但也要体谅他们的怀疑; 如果你能等待,不因等待而疲惫,如果你能被欺骗,不要处理谎言,如果你被憎恨,不要让位于憎恨,如果你看起来不太好,也不要说话太聪明

enter code here


print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))