Tha*_*ser 5 python error-handling invalid-characters
我正在制作检查字符串(电子邮件)的算法 - 就像"电子邮件地址有效",但它们是规则.电子邮件的第一部分必须是包含1-8个字符的字符串(可以包含字母,数字,下划线[_] ...电子邮件包含的所有部分)以及@电子邮件的第二部分之后拥有1-12个字符的字符串(也包含所有合法表达式),它必须以顶级域名.com结尾
email = raw_input ("Enter the e-mail address:")
length = len (email)
if length > 20
print "Address is too long"
elif lenght < 7:
print "Address is too short"
if not email.endswith (".com"):
print "Address doesn't contain correct domain ending"
try:
first_part = len (splitting[0])
second_part = len(splitting[1])
account = splitting[0]
domain = splitting[1]
list = "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_."
for c in account:
if c not in list:
print "Invalid char", "->", c,"<-", "in account name of e-mail"
for c in domain:
if c not in list:
print "Invalid char", "->", c,"<-", "in domain name of e-mail"
if first_part == 0:
print "You need at least 1 character before the @"
elif first_part> 8:
print "The first part is too long"
if second_part == 4:
print "You need at least 1 character after the @"
elif second_part> 16:
print "The second part is too long"
except IndexError:
print ""The address must consist of 2 parts connected with symbol @,\
and ending must be .com"
if first_part > 0 and first_part < 8 and second_part >4 and second_part < 16:
print "Valid e-mail address"
Run Code Online (Sandbox Code Playgroud)
如果我理解得很好,那么除了查找无效字符的部分之外,一切都正常。真的吗?
你知道for循环吗?这可能对你有帮助。只需获取电子邮件的部分内容即可:
account = splitting[0]
domain = splitting[1]
Run Code Online (Sandbox Code Playgroud)
然后,迭代每个部分。每次都会产生一个字符。如果此字符不在允许的字符集中,则打印一条消息:
for c in account:
if c not in "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.":
print "Invalid char", c, "in e-mail"
for c in domain:
if c not in "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.":
print "Invalid char", c, "in e-mail"
Run Code Online (Sandbox Code Playgroud)
这不是一个非常优雅的解决方案(例如,可以使用代替或list comprehesions),但我敢打赌它对于新用户来说是足够容易理解的。string.ascii_letters+string.digits+"._""abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_."