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?

Sumanth
  • 115
  • 1
  • 1
  • 5
  • 1
    `if match: return match.group(1)` will work. No other explicit returns are needed. – DYZ Jan 29 '17 at 00:21
  • `return match.group(1) if match else None` – Peter Wood Jan 29 '17 at 00:23
  • @PeterWood Nope. There is no need to `return None`: any python function always implicitly returns `None` if there are no explicit returns. – DYZ Jan 29 '17 at 00: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](http://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator). Also, [explicit is better than implicit](https://www.python.org/dev/peps/pep-0020/). – Peter Wood Jan 29 '17 at 00:26

2 Answers2

1

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

if match is None
Harald Nordgren
  • 11,693
  • 6
  • 41
  • 65
  • Agreed. But, I was looking for an something other than `if` statement. Something like `with` statement. – Sumanth Jan 29 '17 at 04:40
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.
Community
  • 1
  • 1
ryugie
  • 181
  • 1
  • 1
  • 7