I have a list of email addresses and I would like to remove everything after "@". My code looks like this so far:
user_emails = ['me@organization.org', 'you@organization.org', name@organization.org']
emails = [user.rstrip("@") for user in user_emails]
But nothing changes when I run this code. When I run:
emails = [user.strip("@organization.org") for user in user_emails]
The @ is removed but so is the character to the left of it, which is no good for me.
Is there something I should be doing to remove this character?
Thanks for any insight.
rstrip("@")
doesn't work because there is no @
on the right of the string.
rstrip("@organization.org")
removes more than @organization.org
when there is an O, R, G, A, N, I, Z, T, O, or N at the end of the username portion of the email address. Remember that rstrip()
(and its cousins) remove any of the listed characters, not the string you provide.
A common solution is to split on the @
symbol and take the first item of the returned list.
addresses = [addr.split("@", 1)[0] for addr in user_addresses]
(Naming is important. I used user_addresses
instead of user_email
because you don't have the users' e-mails, you have their e-mail addresses.)
The common solution does create a (small) temporary list for each address processed. This memory is reused almost immediately by the next iteration, so it is unlikely to have any serious detrimental effects. Still, if you want to avoid creating lists you don't need, you can use str.find()
to find the @
and slice off the domain part.
addresses = [addr[:addr.find("@")] for addr in user_addresses]