Reputation:
I'm trying to determine whether a string is an email or not. The requirements are of course the @email.com, the first letter has to be capital and it has to be alphanumeric, except for the @ and the period. What I was looking for is whether there is a way for me to check whether the email is alphanumeric, except for the period and the @
What I would like is for the code to return True for the email if and only if the first letter is capital, it has the @emuail.com and it is alphanumeric except for the @ and the period. What I would like is a solution that checks for alphanumerics except for the @ and the period in the @emauil.com portion of the email.
I was thinking I could separate the email at the @email part and check for .isalnum for everything before the @email, but I just wanted to see if there was an easier way.
Here is my current code, which of course returns all False, because of the @ and the period:
emails = ['[email protected]', '[email protected]', '[email protected]']
result = []
for idx, email in enumerate(emails):
if '@emuail.com' in email and email[0].isupper() and email.isalnum():
result.append(True)
else:
result.append(False)
print(result)
Upvotes: 0
Views: 177
Reputation: 71
This generator will return valid emails. If you want more rules, add them to the condition. re
is better, however.
emails = ['[email protected]', '[email protected]', '[email protected]']
[i for i in emails if '@' in i and i[-4:] == '.com' and i.split('@')[0].isalnum() and '@' is not i[-5]]
Upvotes: 0
Reputation: 2304
When doing string searching/testing that gets even modestly complicated, it's usually better (more readable and more flexible) to use regular expressions.
import re
# from https://emailregex.com/
email_pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
emails = ['[email protected]', '[email protected]', '[email protected]']
for email in emails:
if email_pattern.match(email):
print(email)
Note that hyphens are allowed in email addresses, but if you want to disallow them for some reason, delete them from the regular expression.
Upvotes: 1