我在字符串上使用 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/