I want to extract first name from email address. The email format is <first_name>@gmail.com. If email is not matched return None. I've written the following python code
def getFirstName(email):
email_re = re.compile(r'(\w+)@gmail.com')
match = email_re.search(email)
if match == None:
return None
return match.group(1)
The None checking part looks ugly. Can someone suggest better pythonic way of doing it?
if match: return match.group(1)will work. No other explicit returns are needed.return match.group(1) if match else Nonereturn None: any python function always implicitly returnsNoneif there are no explicit returns.matchis notNonebefore callinggroupon it, otherwise it's returningNone. This is using Python's ternary operator. Also, explicit is better than implicit.