字符串find()、rfind()、index()及count()方法使用
时间: 2024-05-11 11:19:37 浏览: 11
这些方法都可以用于字符串的查找操作。
- `find(substring, start, end)` 方法在字符串中查找子串 `substring`,并返回子串第一次出现的索引值。如果没有找到,则返回 -1。`start` 和 `end` 参数指定查找的起始位置和结束位置,默认为整个字符串。
- `rfind(substring, start, end)` 方法和 `find()` 方法类似,但是是从字符串的末尾开始查找子串 `substring`,并返回最后一次出现的索引值。
- `index(substring, start, end)` 方法和 `find()` 方法类似,但是如果没有找到子串 `substring`,则抛出一个异常。如果找到了,就返回子串第一次出现的索引值。
- `count(substring, start, end)` 方法统计子串 `substring` 在字符串中出现的次数。`start` 和 `end` 参数指定查找的起始位置和结束位置,默认为整个字符串。
下面是一些示例:
```python
# 示例字符串
s = "hello world"
# 查找子串
print(s.find("world")) # 输出 6
print(s.rfind("l")) # 输出 9
print(s.index("l")) # 输出 2
print(s.count("l")) # 输出 3
# 查找不存在的子串
print(s.find("python")) # 输出 -1
print(s.index("python")) # 抛出 ValueError 异常
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)