0

所以这是我的代码(注意微小的语法错误:

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 个字符的用户 ID,格式为 1 个大写字母、2 个小写字母和 3 个数字

ABC123

我在这里遇到了一个问题

elif UserID[3:] > ord(UserID[3:]):
    print("Wrong Format")

其中 ord() 函数无法评估列表的 ASCII 等价物。我知道它应该是针对角色的,所以我不知道该怎么做。这部分代码是为了确保从第 3 个元素开始的任何数字都是一个数字,因此它小于 9 的 ascii 等价物。

4

3 回答 3

1

要查看字符串是否仅由整数组成,您可以使用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")
于 2016-03-11T18:20:46.100 回答
1

仅供参考,以下是使用正则表达式验证整个用户名的方法;

import re

if re.match('^[A-Z][a-z]{2}[0-9]{3}$', UserID):
    print("Correct Format")
else:
    print("Wrong Format")

在您现有的代码中,要检查它们都是您不需要的数字ord,您只需比较它们之间09包含的所有字符;

if not all(c >= '0' and c <= '9' for c in UserID[3:]):
    print("Wrong format")
于 2016-03-11T18:21:22.240 回答
0

可以简化为:

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")
于 2016-03-11T18:36:09.103 回答