这是我的代码(注意微小的语法错误:
UserID = input("Please enter your UserID ")
if len(UserID) !=6:
print("Wrong Format")
elif UserID[:1] == (UserID[:1]).lower():
print("Wrong Format")
elif UserID[1:3] == (UserID[1:3]).upper():
print("Wrong Format")
elif UserID[3:] > ord(UserID[3:]):
print("Wrong Format")
else
print("Correct Format")
基本上,该程序的目的是具有6个字符的UserID,其中1个大写字母,2个小写字母和3位数字的格式
ABC123
我在这里遇到了一个问题
elif UserID[3:] > ord(UserID[3:]):
print("Wrong Format")
其中 ord() 函数无法计算列表的 ASCII 等效项。我知道这应该是针对角色的,所以我不知道该怎么办。代码的这一部分是为了确保从第三个元素开始的任何数字都是一个数字,因此它小于 9 的 ascii 等效值。
要查看字符串是否仅由整数组成,可以使用str.isdigit()
elif not UserID[3:].isdigit():
print("Wrong Format")
显然,(从注释中),有些事情str.isdigit()
返回 True,即使它不是整数。 要解决此问题,请执行以下操作:
elif not all(c in "0123456789" for c in UserID[3:]):
print("Wrong Format")
仅供参考,以下是使用正则表达式验证整个用户名的方法;
import re
if re.match('^[A-Z][a-z]{2}[0-9]{3}$', UserID):
print("Correct Format")
else:
print("Wrong Format")
在现有代码中,要检查它们都是数字,您不需要ord
,您只需比较它们介于 0
和9
(含)之间的所有字符;
if not all(c >= '0' and c <= '9' for c in UserID[3:]):
print("Wrong format")
可以简化为:
UserID = input("Please enter your UserID ")
if ( (len(UserID) !=6) or UserID[0].islower()
or UserID[1:3].isupper() or not UserID[3:].isdigit() ) :
print("Wrong Format")
else
print("Correct Format")