Python 中的 find() 函数有助于返回给定子字符串的位置。如果出现多次,它将返回第一次出现的位置。如果未找到搜索的子字符串,它将返回 -1。
str.find(sub[, start[, end]] ) #where start & end must be an integers
find() 函数接受三个参数。如果 start 和 end 参数缺失,它将把 0 作为起始索引,把 length-1 作为结束参数。
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| sub | 要查找索引的子字符串 | 必需 |
| 开始 (start) | 字符串中搜索应开始的位置。默认为 0 | 可选 |
| end | 搜索应进行到的位置。默认为字符串的末尾 | 可选 |
返回值始终是一个整数值,指定子字符串的位置或索引。此方法类似于 index() 方法,不同之处在于,如果未找到搜索的子字符串,index() 会抛出异常。
| 输入 | 返回值 |
|---|---|
| 如果找到子字符串 | 索引值 |
| 如果未找到子字符串 | -1 |
string = 'What is the, what is the, what is the'
# first occurance of 'what is'(case sensitive)
result = string.find('what is')
print("Substring 'what is':", result)
# find returns -1 if substring not found
result = string.find('Hii')
print("Substring 'Hii ':", result)
# How to use find() in conditions
if (string.find('is,') != -1):
print("Contains substring 'is,'")
else:
print("Doesn't contain substring")
输出
Substring 'let it': 13 Substring 'small ': -1 Contains substring 'is,'
string = 'What is your name'
# Substring is searched in 'your name'
print(string.find('your name', 7))
# Substring is searched in ' is your'
print(string.find('is your', 10))
# Substring is searched in 'what is'
print(string.find('what is', 8, 16))
# Substring is searched in 'is your'
print(string.find('is your ', 0, 14))
输出
8 -1 -1 5