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


123

因此,如果我的字符串是“花花公子很酷”。
我想找到'dude'的第一个索引:

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

这是什么python命令?
谢谢。

Answers:


213

find()

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

20
-1如果找不到,它将返回
Christophe Roussy

如果我想is从句子中找到单词this is a cool dude怎么办?我尝试了find方法,但它返回的是索引2而不是5。如何使用find()实现此目的?
回归器

@Regressor:研究正则表达式和单词边界。
mechanical_meat

27

快速概述: 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

在一般情况下,发现和指数收益率,其中传入的字符串开始最小的指数,并rfindrindex返回它开始大部分的字符串搜索算法进行搜索的最大索引从左到右,所以开始的功能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:Visual快速入门指南,Toby Donaldson


如果将字符串定义为input_string = "this is a sentence"并且如果我们希望找到单词的第一个出现is,那么它将起作用吗? # first occurence of word in a sentence input_string = "this is a sentence" # return the index of the word matching_word = "is" input_string.find("is")
回归器

1

通过不使用任何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 = 'dude1'
print(find_pos(string,word))
# output 4

0
def find_pos(chaine,x):

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

6
好像您的缩进已关闭,并且您忘记了关闭引号。解释您的代码以及为什么它可以解决问题也很有帮助;参见如何回答
camille

抱歉,我对其进行了编辑...我的代码找到了字符串中第一个出现的字母并返回他的位置
Benmadani Yazid
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.