python 字符串查找内容
时间: 2023-07-26 16:38:41 浏览: 135
你可以使用 Python 中的 `find()` 或 `index()` 方法来查找字符串中是否包含某个子串,如果包含则返回子串的起始位置,否则返回 -1。这两个方法的主要区别在于当字符串中不存在子串时,`find()` 方法返回 -1,而 `index()` 方法会抛出一个 ValueError 异常。例如:
```python
str1 = "Hello, world!"
if str1.find("world") != -1:
print("包含子串 'world'")
else:
print("不包含子串 'world'")
try:
idx = str1.index("Python")
except ValueError:
print("不包含子串 'Python'")
else:
print("包含子串 'Python',起始位置为", idx)
```
输出结果为:
```
包含子串 'world'
不包含子串 'Python'
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)