我现在正在为好玩编写一个小系统(用Python编写)。我写邮件检查器时遇到了麻烦。它应该检查电子邮件地址是否包含“.”还有“@”这是代码:
def check_mail(mail):
email = str(mail)
needed_charachters = ['@', '.']
if needed_charachters[1] not in email:
print(send_error('Mail invalid (has to contain ".")'))
return False
if needed_charachters[0] not in email:
print(send_error('Mail invalid (has to contain "@")'))
return False
elif '.' in email:
print('contains .') 我已经尝试了一些技巧,但每次都会出现同样的错误。如果我在邮件中输入"ahksdasdhk“,那么我的错误就”必须包含“,”没关系,这是我想要的。“但是当邮件是"gaagsggg@ksdkj.wssf“时,仍然会出现同样的错误。顺便说一下,这是我的错误创建者代码:
def send_error(message):
return f'ERROR: {message}'发布于 2021-05-10 10:47:46
最后一个问题是elif '.'。你可以做这样的事
def check_mail(mail):
email = str(mail)
if not email.__contains__("@"):
print(send_error('Mail invalid (has to contain "@")'))
return False
if not email.__contains__("."):
print(send_error('Mail invalid (has to contain ".")'))
return False
# if you passed those steps its valid email so
return True或者更简单
def check_mail(mail):
email = str(mail)
needed_charachters = ["@", "."]
err = [x for x in needed_charachters if x not in email]
err and print(send_error(f"Mail invalid (has to contain '{err[0]}')"))
return not bool(err)然而,我自己总是像这样核实电子邮件
import re
regex = """^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$"""
is_valid_email = lambda email: bool(re.search(regex, email))
# checking if email is valid or not
print(is_valid_email("the_email_address@info.com"))发布于 2021-05-10 09:52:37
elif是问题所在,请尝试如下:
def check_mail(mail):
email = str(mail)
needed_charachters = ['@', '.']
if needed_charachters[1] not in email:
print(send_error('Mail invalid (has to contain ".")'))
return False
if needed_charachters[0] not in email:
print(send_error('Mail invalid (has to contain "@")'))
return False
else:
print('Valid mail')
return True并建议在循环中这样做:
def check_mail(mail):
email = str(mail)
needed_charachters = ['@', '.']
for character in needed_characters:
if character not in email:
print(send_error('Mail invalid (has to contain ' + character + ')'))
return False
else:
print('Valid mail')
return Truehttps://stackoverflow.com/questions/67468196
复制相似问题