温馨提示×

python字符串find方法怎么使用

小亿
88
2023-12-08 17:41:39
栏目: 编程语言

字符串的 find() 方法可以用来查找一个子字符串在原字符串中的位置。它的语法格式为:

str.find(sub[, start[, end]])

其中,str 是原字符串,sub 是要查找的子字符串,start 是可选参数,表示开始查找的起始位置,默认为 0,end 是可选参数,表示结束查找的位置,默认为字符串的长度。

find() 方法会返回子字符串在原字符串中第一次出现的位置,如果找不到则返回 -1。以下是一些示例:

# 在字符串中查找子字符串
s = "Hello, world!"
index = s.find("world")  # 返回 7
print(index)

# 在指定位置范围查找子字符串
s = "Hello, world!"
index = s.find("o", 5, 10)  # 返回 7(从索引5到索引10之间查找)
print(index)

# 查找不存在的子字符串
s = "Hello, world!"
index = s.find("Python")  # 返回 -1
print(index)

注意,在 Python 中字符串的索引是从 0 开始的。

0