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")
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")
推荐阅读
- flutter - 如何在 Flutter 中的脚手架负载上显示小吃栏?
- javascript - 默认图片取代用户头像(laravel)
- git - 如何仅允许提交 Azure DevOps 中的特定名称/电子邮件?
- solr - Solr 指标 API 获取文档数量
- ckeditor - 如何将 html 添加到 ckeditor 的自定义插件中?
- r - 如何在超级账本作曲家休息服务器的 POST 请求中为参数提供空值
- workflow - Bitrise 本地路径证书和临时配置文件
- android - 如何在 Flutter 应用程序中设置 facebook 帐户工具包
- python - python如何在其中找到修饰函数?
- sql - 从 Oracle 中的字符串中删除重音符号