为什么我的 python 代码显示我不想要的东西?



对不起,我认为这个问题的标题不合适。所以我想问,在我成为PHP用户之前,我碰巧是python的初学者。出现这个问题是因为python在找不到它要找的东西时总是显示一个错误,如下面的代码所示:

import re
txt = "The rain mantap bang in Spain"
x = re.findall("mantap jiwa", txt)
if x[0] == 'mantap jiwa':
print("found")
else:
print("not found")

Traceback(最后一次调用(:文件"./prog.py",第6行,位于IndexError:列出超出范围的索引

为什么python不显示"未找到"?为什么必须显示错误,如何使python显示"未找到"?

尝试访问x的第一个元素(通过说x[0](会引发异常,因为x为空,因此没有第一个元素:

>>> txt = "The rain mantap bang in Spain"
>>> x = re.findall("mantap jiwa", txt)
>>> x
[]

测试某个东西是否在集合(列表、集合等(中的最佳方法是简单地使用in运算符:

if 'mantap jiwa' in x:
print("found")
else:
print("not found")

由于如果您没有找到匹配项,x将始终为空,因此检查匹配项的实际内容对于您正在执行的操作来说是不必要的。你可以问x是否包含任何东西:

if len(x) >= 0:
print("found")
else:
print("not found")
if x:  # truthy check -- x is "true" if it has at least one element
print("found")
else:
print("not found")

或者,您可以使用原始代码,但发现异常:

try:
if x[0] == 'mantap jiwa':
print("found")
else:
raise IndexError()
except IndexError:
print("not found")

最新更新