如何在python字符串中找到子字符串的第一个匹配项?
所以如果我的字符串是“这家伙很酷”。如何在python字符串中找到子字符串的第一个匹配项?,python,string,Python,String,所以如果我的字符串是“这家伙很酷”。 我想找到“dude”的第一个索引: mystring.findfirstindex('dude') # should return 4 什么是用于此的python命令? 谢谢。 快速概述:索引和查找 在find方法旁边还有indexfind和index都会产生相同的结果:返回第一次出现的位置,但是如果没有找到index将产生ValueError,而find返回-1。就速度而言,两者的基准测试结果相同 s.find(t) #returns: -1, o
我想找到“dude”的第一个索引:
mystring.findfirstindex('dude') # should return 4
什么是用于此的python命令?谢谢。 快速概述:
索引
和查找
在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
:
通常,find和index返回传入字符串开始处的最小索引,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 QuickStart Guide,Toby Donaldson以算法方式实现此功能,不使用任何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(链,x):
对于范围内的i(len(chaine)):
如果链[i]==x:
返回“是”,我
返回“否”
诗句=“如果你能在周围的人都失去理智并责怪你的时候保持冷静,如果你能在所有人都怀疑你的时候相信自己,但也要体谅他们的怀疑\如果你能等待而不因等待或被欺骗而感到疲倦,那么就不要说谎,也不要被憎恨,不要让位于憎恨,但不要看起来太好,也不要说得太明智:
如果未找到,则返回
-1
,如果我想从句子中找到单词是什么,这是一个很酷的家伙
?我尝试了find方法,但它返回索引2而不是5。如何使用find()实现这一点?@Regressionor:查看正则表达式和单词边界。似乎您的缩进已关闭,而您忘记了关闭引号。解释您的代码以及它解决问题的原因也很有帮助;请参阅抱歉,我编辑了它…如果字符串中定义了,我的代码将查找字符串中第一个字母并返回其位置put_string=“this is a句子”
如果我们希望找到单词的第一个匹配项is
,那么它会起作用吗?#单词在句子中的第一个匹配项input_string=“this is a句子”#返回匹配单词的索引_word=“is”input_string.find(“is”)
欢迎使用Stack Overflow。您回答的是一个旧的、已经回答过的问题(用绿色复选标记回答),但没有提供更多信息或更好的解释。因此,它基本上只是重复了。请看。(为了进一步参考,请看)。
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
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))