域名后缀错误检查;如何在电子邮件地址中'.'后限制字符限制?


#Takes user's email and stores it in a variable
userEmail = input("Please enter email: ").lower()
while '@' not in userEmail or '.com' not in userEmail or userEmail == '':       #Checks if email has a valid format
if (userEmail == ''):
userEmail = input("Field is empty. Please enter an email address: ").lower().strip()
else:
userEmail = input("nIncorrect format. Please re-enter email address: ").lower().strip()

因此,上面的代码应该从用户那里获得电子邮件地址,并在输入时错误检查用户是否输入了.com@

但是,当我运行代码时;如果用户输入的是CCD_ 3或CCD_。

有什么方法可以限制用户在字符串中某个字符之后可以输入的字符数?

有什么方法可以限制用户在字符串中某个字符之后可以输入的字符数?

要将.后面的字符数限制在2到4之间,可以使用rpartition:

while True:
email = input("Enter a valid email address: ").strip()
if "@" in email:
if 2 <= len(email.rpartition(".")[-1]) <= 4:
# TLD length is acceptable; stop prompting
break
print("You entered {e}.".format(e=email))

。。。检查用户在输入时是否输入了'.com'和'@'。

如果这些是您的实际标准:

email = None
while ("@" not in email) or not email.endswith(".com"):
email = input("Enter a valid email address: ").strip()
print("You entered {e}.".format(e=email))

不过,这仍然不能接近于验证电子邮件地址的格式。虽然这不是你所问的,但如果你感兴趣,在回答这个问题时会讨论各种方法。

最新更新