查找和索引的区别 [英] difference between find and index

查看:94
本文介绍了查找和索引的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,不太明白 find 和 index 之间的区别.

<预><代码>>>>线这是 ABC,我的天啊!!">>>line.find("o")16>>>line.index("o")16

它们总是返回相同的结果.谢谢!!

解决方案

str.find 在没有找到子串时返回 -1.

<预><代码>>>>line = '这是 ABC 哦,我的天啊!!'>>>line.find('?')-1

虽然str.index 引发 ValueError:

<预><代码>>>>line.index('?')回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>值错误:未找到子字符串

如果找到子字符串,这两个函数的行为方式相同.

I am new to python and cannot quite understand the difference between find and index.

>>> line
'hi, this is ABC oh my god!!'
>>> line.find("o")
16
>>> line.index("o")
16

They always return the same result. Thanks!!

解决方案

str.find returns -1 when it does not find the substring.

>>> line = 'hi, this is ABC oh my god!!'
>>> line.find('?')
-1

While str.index raises ValueError:

>>> line.index('?')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

Both the functions behave the same way if a sub-string is found.

这篇关于查找和索引的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆