Reputation: 105
I need to write a script to "validate" email addresses by taking user input and checking that the string is separated into 2 segments by an '@' symbol (it's honestly pointless - I know).
I can figure out validating the '@' symbol, but I can't seem to figure out how to implement this to validate that the '@' separates the string into 2 segments. I honestly don't know where to start.
print ("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
print ("\n Welcome to my Email Address Validator!")
print (" You can use this tool to check the validation of email addresses.")
print("\n Please input the email address that you would like to validate.")
print ("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
def email_check():
address = str(input("\n Email Address: "))
if "@" in address:
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
print ("\n This is a valid email address!")
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
return email_check()
else:
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
print ("\n This is an invalid email address!\n No @ symbol identified!")
print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
return email_check()
email_check()
Upvotes: 1
Views: 1621
Reputation: 46
Probably the simplest way to handle this is by using a regular expression (regex), as although it is possible with raw Python (namely by using str.split() and checking the returned values) your code will be much harder to parse.
Here is a regex that should only match with valid email addresses:
^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$
You can use this tool to test that against your cases. It also offers explanations for each component of the expression when you hover over them.
And in use:
import re
def valid_email(address):
valid_email_regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
if not re.search(valid_email_regex, address):
return False
return True
Upvotes: 2
Reputation: 2096
You can use regular expressions to check if the String has an '@' symbol in the middle:
import re
address = str(input("\n Email Address: "))
if(re.match('.+@.+', address)):
print("address has '@' in the middle")
.+@.+
is a regular expression that checks if the String has 1 or more characters (.+
) before and after the symbol '@'.
To check if the String does not contain whitespaces, simply use the not in
operator:
if(' ' not in address):
print("address does not contain whitespaces")
Upvotes: 2
Reputation: 129
You can use str.split() and maybe use regular expressions.
https://www.geeksforgeeks.org/python-string-split/
However, instead of checking if there are spaces in email address, simply find and delete them using str.split(' ') and create valid email.
Upvotes: 1