2013-03-07 118 views
2

我在字符串上使用index()来查找子字符串的出现。如何处理ValueError?

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

"ValueError: substring not found". 

我想我的程序能够在发生这种情况承认,但我不知道如何打开ValueError成有用的东西。例如,如何在if声明中使用ValueError

回答

4

不要等待异常。使用find()而不是index(),你将避免有例外。只需测试未找到并完成它。

5

通常你可以使用try和除了捕获异常,但在这种情况下,如约翰所说,你可以使用find()。

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