我正在使用index()字符串来查找子字符串的出现.
当字符串中不存在子字符串时,我得到:
"ValueError: substring not found".
Run Code Online (Sandbox Code Playgroud)
我希望我的程序能够识别何时发生这种情况,但我不知道如何将其ValueError转化为有用的东西.例如,我如何ValueError在if声明中使用a ?
通常你可以使用try除了捕获异常,但在这种情况下,如John所提到的,你可以使用find().
try:
#your code that raises the exception
except ValueError:
#turn it into something useful
Run Code Online (Sandbox Code Playgroud)