Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression evaluating to None when substr is not found

Tags:

python

string

str.find() always returns -1 if not found. Can I write an expression instead of str.find() and return None if not found?

like image 258
ThunderEX Avatar asked Nov 22 '12 08:11

ThunderEX


1 Answers

Do you mean something like this?

def find2(str, substr):
    result = str.find(substr)
    return result if result != -1 else None

In Python 2.4, change the last line to

    if result != -1:
        return result 
    else:
        return None
like image 75
Will Vousden Avatar answered Sep 23 '22 19:09

Will Vousden