方法和函数是一回事,只是它是调用在一个值上。例如,如果一个列表值存储
在 spam 中,你可以在这个列表上调用 index()列表方法(稍后我会解释),就像 spam.index('hello')一样。方法部分跟在这个值后面,以一个句点分隔。
每种数据类型都有它自己的一组方法。例如,列表数据类型有一些有用的方法,用来查找、添加、删除或操作列表中的值。
用 index()方法在列表中查找值
列表值有一个 index()方法,可以传入一个值,如果该值存在于列表中,就返回它的下标。如果该值不在列表中,Python 就报 ValueError。在交互式环境中输入以下代码:
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module> spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
如果列表中存在重复的值,就返回它第一次出现的下标。在交互式环境中输入以下代码,注意 index()返回 1,而不是 3:
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1