Search code examples
pythonpython-3.xoverridingbuilt-in

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'))

it obviously returns -1 but also an exception, so my question is simply how to remove the exception from the output and let -1 as the output only.


Solution

  • I would rather say handle the exception instead of trying to override the built-in function like:

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

    But if you still want to override it here is one of the approach:

    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'))