Python中的ASCII密码验证

2024-04-20 10:50:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的大学有一项任务(我是初学者),要求你使用ASCII字符验证密码。我尝试使用简单的代码,但它一直跳过我的ASCII部分。 要求清单:

1.4 Call function to get a valid password OUT: password
1.4.1 Loop until password is valid 1.4.2 Ask the user to enter a password 1.4.3 Check that the first character is a capital letter (ASCII values 65 to 90) 1.4.4 Check that the last character is #, $ or % (ASCII values 35 to 37) 1.4.5 Return a valid password

U = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
upCase = ''.join(chr(i) for i in U)
print(upCase) #Ensure it is working

def passVal(userPass):
    SpecialSym = ["#", "$", "%"]
    val = True

#Common way to validate password VVV
    if len(userPass) < 8:
        print("Length of password should be at least 8")
        val = False
    if not any(char.isdigit() for char in userPass):
        print("Password should have at least one numeral")
        val = False

#I Tried same with ASCII (and other methods too) but it seemed to be skipping this part VVV
    if not any(upCase for char in userPass):
        print("Password should have at least one uppercase letter")
        val = False


    if not any(char.islower() for char in userPass):
        print("Password should have at least one lowercase letter")
        val = False
    if not any(char in SpecialSym for char in userPass):
        print("Password should have at least on fo the symbols $%#")
        val = False
    if val:
        return val


def password():
    if (passVal(userPass)):
        print("Password is valid")
    else:
        print("Invalid Password !!")

userPass = input("Pass: ")
password()

Tags: toinforifisasciivalpassword
1条回答
网友
1楼 · 发布于 2024-04-20 10:50:29

在Python3.7中,您可以使用str.isascii()

>>> word = 'asciiString'
>>> word.isascii()
True

否则,您可以使用:

>>> all([ord(c) < 128 for c in word])
True

由于所有ASCII字符的序数(ord)值都小于128(0->;127):https://en.wikipedia.org/wiki/ASCII

因此,您的逻辑将为(3.7+):

if word.isascii():
    # string is ascii
...

或:

if all([ord(c) < 128 for c in word]):
    # string is ascii
else:
    # string contains at least one non-ascii character

相关问题 更多 >