0

I know how to use email.utils.parseaddr to parse an email address such as

"Foo" <bar@quack.com>

into the following 2-tuple:

('Foo', 'bar@quack.com').

I also know how to use the split() function to turn the address portion into this tuple:

('bar', 'quack.com').

But what I'm looking for a pre-existing module which contains a function which will parse that address into this 3-tuple:

('Foo', 'bar', 'quack.com').

I can trivially write such a function, and I have done so on numerous occasions. But what I'm looking for is an already-existing module that provides an already-defined function that will produce such a 3-tuple when given any email address.

I haven't been able to find such a thing. Can anyone point me to something like this which might already be in existence?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
HippoMan
  • 2,119
  • 2
  • 25
  • 48

1 Answers1

0

If it's always in the same format, you could do:

>>> import re
>>> s = '"Foo" <bar@quack.com>'
>>> tuple([item.strip('"><') for item in re.split(r'\s|@', s)])
('Foo', 'bar', 'quack.com')
David542
  • 104,438
  • 178
  • 489
  • 842
  • Thank you. Yes, I already do pretty much the same thing in my own hand-written code. I'm just looking for a pre-existing package which I can use in place of email.util which might already contain a function like this. – HippoMan Dec 15 '16 at 22:46
  • 1
    I think it's better to use the two-liner `def emlparse(addr): nam, addr = email.utils.parseaddr(addr); return (nam, *addr.split('@'))` since this will correctly deal with other formats such as `bar@quack.com (Foo)`. However, both these will fail with an address such as `"lal@la"@example.com`, which is [actually valid](https://en.wikipedia.org/wiki/Email_address#Examples) (note the quotes). – Nick Matteo Dec 15 '16 at 23:36