在 Python 中覆盖 idex() 函数的任何技巧,因此如果找不到字符串则不会引发异常

Any trick to override idex() function in Python so exception won't be raised if a string is not found

a = 'abc'
print(a.index('q'))

显然 returns -1 但也是一个异常,所以我的问题只是如何从输出中删除异常并只让 -1 作为输出。

我宁愿说处理异常而不是尝试覆盖内置函数,如:

try:
    ind = string.index(substring)
    print (ind)
except:
    return f"{substring} does not exist in {string}"

但如果您仍想覆盖它,这里有一种方法:

def index(string, substring):
    try:
        ind = string.index(substring)
        return ind
    except:
        return f"{substring} does not exist in {string}"
    
a = "abc"
print(index(a, 'c'))