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
发布了78 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_43657442/article/details/103066405