Reputation: 115
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?
Upvotes: 2
Views: 147
Reputation: 181
def get_first_name(email):
match = re.search(r'(\w+)@gmail\.com', email)
return match.group(1) if match else None
.
in your pattern or else it'll match anything.with
statement is not relevant here.Upvotes: 0
Reputation: 12391
This is the Pythonic way of handling this. Well almost.
if match is None
Upvotes: 1