python find用法
时间: 2023-08-05 21:09:52 浏览: 37
`find()` 是 Python 字符串的一个方法,用于查找字符串中是否包含某个子字符串,并返回第一个匹配的位置。如果没找到,则返回 -1。`find()` 方法的语法如下:
```python
str.find(sub[, start[, end]])
```
其中,`sub` 是要查找的子字符串,`start` 和 `end` 是可选参数,指定搜索的起始位置和结束位置。
例如,查找字符串 `"hello world"` 中是否包含子字符串 `"world"`,可以这样写:
```python
str = "hello world"
pos = str.find("world")
print(pos)
```
运行结果为:`6`,表示子字符串 `"world"` 在字符串 `"hello world"` 中的位置是 6。
如果要从指定的位置开始查找,可以传递 `start` 参数:
```python
str = "hello world"
pos = str.find("l", 3)
print(pos)
```
运行结果为:`3`,表示从位置 3 开始,第一次出现字母 `"l"` 的位置是 3。
如果要指定搜索的结束位置,可以传递 `end` 参数:
```python
str = "hello world"
pos = str.find("l", 3, 6)
print(pos)
```
运行结果为:`3`,表示从位置 3 开始,到位置 6 结束,在这个范围内第一次出现字母 `"l"` 的位置是 3。注意,搜索范围是左闭右开区间,即不包括结束位置。