find()
函数是 Python 字符串对象的一个内置方法,用于查找子字符串在主字符串中的位置。如果找到子字符串,则返回其第一次出现的索引;如果没有找到,则返回 -1。
语法:
str.find(sub[, start[, end]])
sub
:要查找的子字符串。start
(可选):搜索的起始位置。end
(可选):搜索的结束位置。类型:
应用场景:
# 基本用法
text = "Hello, world!"
result = text.find("world")
print(result) # 输出: 7
# 指定搜索范围
result = text.find("o", 5, 10)
print(result) # 输出: 7
# 未找到子字符串
result = text.find("python")
print(result) # 输出: -1
问题1:找不到子字符串时返回值是什么?
if result == -1:
print("子字符串未找到")
else:
print(f"子字符串首次出现在索引 {result}")
问题2:如何处理大小写敏感问题?
find()
是大小写敏感的。text = "Hello, World!"
sub = "world"
result = text.lower().find(sub.lower())
print(result) # 输出: 7
问题3:如何查找多个匹配项?
find()
只返回第一个匹配项的索引。def find_all_occurrences(text, sub):
occurrences = []
start = 0
while True:
index = text.find(sub, start)
if index == -1:
break
occurrences.append(index)
start = index + 1
return occurrences
text = "abracadabra"
sub = "abra"
print(find_all_occurrences(text, sub)) # 输出: [0, 7]
通过这些方法和示例代码,你可以更好地理解和使用 Python 中的 find()
函数。
领取专属 10元无门槛券
手把手带您无忧上云