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

时间:2010-07-11 04:47:56

标签: python string

所以,如果我的字符串是“这个家伙是一个很酷的家伙” 我想找到'dude'的第一个索引:

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

对此有什么蟒蛇命令?
感谢。

5 个答案:

答案 0 :(得分:164)

find()

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

答案 1 :(得分:20)

快速概述:indexfind

find方法旁边还有indexfindindex都会产生相同的结果:返回第一个匹配项的位置,但是如果找不到任何内容index将引发ValueErrorfind返回-1。 Speedwise,两者都有相同的基准测试结果。

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指南,Toby Donaldson

答案 2 :(得分: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

答案 3 :(得分:0)

def find_pos(chaine,x):

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

答案 4 :(得分:0)

verse =“如果您在所有有关您的事情时都能保持头脑\ n失去他们的责任并指责您,\ 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))