Python里面的find()


函数原型:find(str, startIndex, endIndex)

调用形式:Str.find(str,startIndex,endIndex)

解释:

Str:源字符串
str:想要查找的“字符串”。—— 目标字符串
startIndex:查找的首字母位置(从0开始计数。默认:0)
endIndex: 查找的末尾位置(默认-1)

返回值:如果查到:返回第一个出现的位置。否则,返回-1。

例如,

Str="hello world!,hello world!"
str1="llo"
index=Str.find(str1)

index的值是2。

所以find()函数就是在源字符串(Str)中查找第一个与目标字符串(str1)一致的子串(x)。然后返回这个子串(x)的第一个字符(‘l’)在源字符串中的下标位置。

要想查找所有符合的子串的位置呢

def find_all(Str,str1):
	index_list = []
	index = Str.find(str1,0,-1)
	while index != -1:
		index_list.append(index)
		index = Str.find(str1,index+len(str1),-1)
	return index_list if len(index_list) > 0 else -1


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM