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

Time:12-31

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.

CodePudding user response:

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