我如何处理ValueError?

Lie*_*ala 2 python

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

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

"ValueError: substring not found".
Run Code Online (Sandbox Code Playgroud)

我希望我的程序能够识别何时发生这种情况,但我不知道如何将其ValueError转化为有用的东西.例如,我如何ValueErrorif声明中使用a ?

jur*_*eza 6

通常你可以使用try除了捕获异常,但在这种情况下,如John所提到的,你可以使用find().

try:
   #your code that raises the exception
except ValueError:
   #turn it into something useful
Run Code Online (Sandbox Code Playgroud)


Joh*_*nck 5

不要等待异常。使用find()代替,index()您将完全避免出现异常。只需测试未找到的内容并完成它即可。