首页 > 解决方案 > 为什么我的 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显示“未找到”?

标签: 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")

推荐阅读