Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我的python代码会显示我不知道的东西';你不想要吗?_Python - Fatal编程技术网

为什么我的python代码会显示我不知道的东西';你不想要吗?

为什么我的python代码会显示我不知道的东西';你不想要吗?,python,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")

对不起,我认为这个问题的标题不合适。所以我想问,在我成为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")
回溯(最近一次呼叫最后一次): 文件“/prog.py”,第6行,在 索引器:列表索引超出范围


为什么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")
或者您可以使用原始代码但捕获异常:

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

mantap jiwa不在
txt
中,因此它返回一个空字符串
try:
    if x[0] == 'mantap jiwa':
        print("found")
    else:
        raise IndexError()
except IndexError:
    print("not found")