2

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?

4
  • 1
    if match: return match.group(1) will work. No other explicit returns are needed. Commented Jan 29, 2017 at 0:21
  • return match.group(1) if match else None Commented Jan 29, 2017 at 0:23
  • @PeterWood Nope. There is no need to return None: any python function always implicitly returns None if there are no explicit returns. Commented Jan 29, 2017 at 0:24
  • The code isn't the same as yours. It's checking match is not None before calling group on it, otherwise it's returning None. This is using Python's ternary operator. Also, explicit is better than implicit. Commented Jan 29, 2017 at 0:26

2 Answers 2

1

This is the Pythonic way of handling this. Well almost.

if match is None
Sign up to request clarification or add additional context in comments.

1 Comment

Agreed. But, I was looking for an something other than if statement. Something like with statement.
0
def get_first_name(email):
    match = re.search(r'(\w+)@gmail\.com', email)
    return match.group(1) if match else None
  • You need to escape the . in your pattern or else it'll match anything.
  • The with statement is not relevant here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.