Search code examples
pythonif-statementtry-except

How to handle exceptions and specific conditions with the same chunk of Python codes


I wonder if there's any way to make Python execute the same chunk of codes if something happen or if there are errors.

For example, I am writing a function which is able to get characters following a colon in a given string, and I want it to do the same thing if a) there is no colon or b) a colon exists but there's no characters following it. Let's assume there will be at most one colon in a given string.

def split_colon(string):
    try:
        ans = string.split(":")[1].strip()
        return ans
    except IndexError or if ans == "":
        return "Hmm, not a word is found"

Obviously I am getting a SyntaxError in the codes above. How can I achieve my goal not by:

def split_colon(string):
    try:
        ans = string.split(":")[1].strip()
    except IndexError:
        return "Hmm, not a word is found"
    if ans == "":
        return "Hmm, not a word is found"
    else:
        return ans

, which will duplicate the same codes?


Solution

  • string.partition(':')[2]
    

    is the way to go. The resulting string will be empty if no colon exists or no character is following the colon.