Answers:
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
is从句子中找到单词this is a cool dude怎么办?我尝试了find方法,但它返回的是索引2而不是5。如何使用find()实现此目的?
index和find该find方法旁边也有index。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
rfind和rindex:在一般情况下,发现和指数收益率,其中传入的字符串开始最小的指数,并
rfind和rindex返回它开始大部分的字符串搜索算法进行搜索的最大索引从左到右,所以开始的功能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")
通过不使用任何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
def find_pos(chaine,x):
for i in range(len(chaine)):
if chaine[i] ==x :
return 'yes',i
return 'no'
-1如果找不到,它将返回