python - 如何处理 ValueError?

标签 python

我在字符串上使用 index() 来查找子字符串的出现。

当字符串中不存在子字符串时,我得到:

"ValueError: substring not found".

我希望我的程序能够识别这种情况何时发生,但我不知道如何将 ValueError 变成有用的东西。例如,如何在 if 语句中使用获取 ValueError

最佳答案

通常您可以使用 try 和 except 来捕获异常,但在 John 提到的这种情况下,您可以只使用 find()。

try:
   #your code that raises the exception
except ValueError:
   #turn it into something useful

关于python - 如何处理 ValueError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15263561/

相关文章:

python - python os.rename找不到文件,即使代码检查它是否存在

python - PostgreSQL 使用单个脚本 (psycopg2) 分两个阶段导入 CSV 文件

python - 如何使用 Pandas 复制与列表中的日期值匹配的日期时间行

python - 优化裁剪功能

python - 在 DatetimeIndex 上使用 pandas Timestamp 对 DataFrame 进行切片

python - 我无法更改主 Django 项目设置文件

python Gtk.PrintOperation 打印 pdf

python - 防止 lxml 在匹配元素后选择下一个文本节点

python - python中的对象跟踪

python - 彩色图上的轮廓 : not continuous (Python)