Python的index
时间: 2023-11-05 20:04:53 浏览: 26
在 Python 中,`index` 是一个字符串、列表、元组等对象的方法,用于查找给定元素在对象中出现的位置(即索引)。它的语法如下:
```
object.index(element[, start[, end]])
```
其中,`object` 是要查找元素的对象,`element` 是要查找的元素,`start` 是可选参数,表示查找的起始位置,默认为 0,`end` 也是可选参数,表示查找的终止位置,默认为对象的长度。
如果元素在对象中找到了,`index` 方法返回该元素在对象中的索引,否则会抛出 `ValueError` 异常。例如:
```python
>>> lst = [1, 2, 3, 4, 5]
>>> lst.index(3)
2
>>> lst.index(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 6 is not in list
```
在字符串中使用 `index` 方法时,它返回的是子串在字符串中的起始位置。例如:
```python
>>> s = 'hello world'
>>> s.index('o')
4
>>> s.index('world')
6
>>> s.index('hi')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
```
相关推荐
![gz](https://img-home.csdnimg.cn/images/20210720083447.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)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)