如何在Python字符串中找到子串的首次出现?

182 投票
5 回答
308317 浏览
提问于 2025-04-16 01:07

给定字符串 "the dude is a cool dude",
我想找到第一个出现的 'dude' 的位置:

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

在Python中怎么写这个命令呢?

5 个回答

3

要用算法的方式来实现这个,而不使用任何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
56

快速概述:indexfind

除了 find 方法,还有 index。这两个方法的作用是一样的:都能返回你要找的内容第一次出现的位置,但是如果找不到,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

一般来说,findindex 返回的是传入字符串开始的最小位置,而 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

306

find() 是一个用来在字符串中查找某个子字符串的位置的函数。

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

撰写回答