什么是find函数?
find函数是Python中的一个字符串方法,它用于查找指定字符串在另一个字符串中的位置。在Python中,字符串是不可变的,因此find函数返回的是指定字符串在另一个字符串中的索引位置,如果指定字符串不存在,则返回-1。
find函数的语法
find函数的语法如下:
str.find(sub[, start[, end]])
其中,str表示要查找的字符串,sub表示要查找的子字符串,start和end表示查找的起始和结束位置。如果省略start和end,则默认从字符串的开头到结尾进行查找。
find函数的使用
下面是find函数的一些使用示例:
- 查找子字符串在字符串中的位置:
- 查找子字符串在字符串中的位置(指定起始位置):
- 查找子字符串在字符串中的位置(指定起始位置和结束位置):
- 查找不存在的子字符串:
- 查找空字符串:
- 查找多个子字符串:
str = "hello world" sub = "world" index = str.find(sub) print(index) # 6
在上面的示例中,find函数返回了子字符串“world”在字符串“hello world”中的位置,即第7个字符的位置。
str = "hello world" sub = "o" index = str.find(sub, 5) print(index) # 7
在上面的示例中,find函数从位置5开始查找子字符串“o”,返回了子字符串“o”在字符串“hello world”中的位置,即第8个字符的位置。
str = "hello world" sub = "o" index = str.find(sub, 5, 8) print(index) # -1
在上面的示例中,find函数从位置5开始查找子字符串“o”,并指定查找结束位置为位置8,由于子字符串“o”不存在于该范围内,因此返回-1。
str = "hello world" sub = "python" index = str.find(sub) print(index) # -1
在上面的示例中,find函数返回了子字符串“python”在字符串“hello world”中的位置,由于子字符串“python”不存在于该字符串中,因此返回-1。
str = "hello world" sub = "" index = str.find(sub) print(index) # 0
在上面的示例中,find函数返回了空字符串在字符串“hello world”中的位置,即第一个字符的位置。
str = "hello world" sub = "o" index = str.find(sub) while index != -1: print(index) index = str.find(sub, index + 1)
在上面的示例中,通过循环查找字符串中所有的子字符串“o”,并输出它们在字符串中的位置。