find()
方法返回子字符串第一次出现的索引(如果找到)。如果未找到,则返回 -1。
示例
message = 'Python is a fun programming language'
# check the index of 'fun'
print(message.find('fun'))
# Output: 12
find() 语法
find()
方法的语法是
str.find(sub[, start[, end]] )
find() 参数
find()
方法最多接受三个参数
- sub - 要在 str 字符串 中搜索的子字符串。
- start 和 end(可选)- 搜索子字符串的范围
str[start:end]
。
find() 返回值
find()
方法返回一个整数值
- 如果子字符串存在于字符串中,则返回子字符串第一次出现的索引。
- 如果子字符串不存在于字符串中,则返回 -1。
find() 方法的工作原理

示例 1:不带 start 和 end 参数的 find()
quote = 'Let it be, let it be, let it be'
# first occurance of 'let it'(case sensitive)
result = quote.find('let it')
print("Substring 'let it':", result)
# find returns -1 if substring not found
result = quote.find('small')
print("Substring 'small ':", result)
# How to use find()
if (quote.find('be,') != -1):
print("Contains substring 'be,'")
else:
print("Doesn't contain substring")
输出
Substring 'let it': 11 Substring 'small ': -1 Contains substring 'be,'
示例 2:带 start 和 end 参数的 find()
quote = 'Do small things with great love'
# Substring is searched in 'hings with great love'
print(quote.find('small things', 10))
# Substring is searched in ' small things with great love'
print(quote.find('small things', 2))
# Substring is searched in 'hings with great lov'
print(quote.find('o small ', 10, -1))
# Substring is searched in 'll things with'
print(quote.find('things ', 6, 20))
输出
-1 3 -1 9
另请阅读