如何在Python字符串中找到子字符串的第一个出现位置?

181

给定字符串 "the dude is a cool dude",
我想要找到第一个 'dude' 的索引:

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

这个该用哪个Python命令?

5个回答

305

find()

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

45
如果没有找到,它会返回“-1”。 - Christophe Roussy
如果我想从句子“this is a cool dude”中找到单词“is”,该怎么办?我尝试了find()方法,但它返回的是2而不是5。如何使用find()实现这一点? - Regressor
1
@Regressor:研究正则表达式和单词边界。 - mechanical_meat
1
@Regressor 你也可以直接使用s.find(" is ")+1,虽然有点不正规但是完全可行。 - Eog

55

快速概述:indexfind

除了find方法外,还有一个index方法。 findindex都会返回第一次出现的位置,但是如果没有找到,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可视化快速入门指南》,Toby Donaldson


如果字符串被定义为 input_string = "this is a sentence",并且我们希望找到单词 is 的第一次出现,那么这段代码会起作用吗?# 在句子中查找单词的第一次出现 input_string = "this is a sentence" # 返回单词的索引 matching_word = "is" input_string.find("is") - Regressor
@Regressor你可能想要搜索两端带有空格的字符串:'this is a sentence'.find(' is ') - zfj3ub94rf576hc4eegm

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

0
def find_pos(chaine,x):

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

7
看起来您的缩进有误,而且您忘记关闭引号。解释您的代码以及它如何解决问题也会有所帮助;请参见 [答案]。 - camille
抱歉,我编辑了一下...我的代码会在字符串中找到第一个字母出现的位置并返回它。 - Benmadani Yazid

0

诗句 = "如果你能在周围的一切都失控并将其归咎于你时保持冷静,\n如果你能相信自己,即使所有人都怀疑你,\n但也要容忍他们的怀疑;\n如果你能等待而不会因等待而感到疲倦,\n或者被谎言所包围,不要说谎,\n或者被憎恨,不要屈服于仇恨,\n但也不要显得太好,也不要说得太聪明:"

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))

1
欢迎来到Stack Overflow。您正在回答一个旧的已经有答案的问题(带有绿色勾号的答案),但没有提供更多信息或更好的解释。因此,它基本上只是重复了被接受的答案。请查看如何编写好的答案?(并且为了进一步参考,请查看如何处理流行问题上的晚期明显重复的答案(“冲浪”)的清理)。 - Ivo Mori

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接