如何在Python中创建密码检查器?

2024-06-16 10:01:56 发布

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

我正在尝试用Python制作一个简单的密码检查器。 该程序要求用户输入一个包含8个以上字母/符号和if/else语句的密码,如果它不包含上/下字母和数字,但每次我输入一些东西时,它都会打印“密码足够强”,即使我没有输入上/下字母或数字。所以,如果有人能帮助我,我会非常感激

这是代码:

password = input("Input your password: ")

if (len(password)<8):
  print("Password isn't strong enough")
elif not ("[a-z]"):
  print("Password isn't strong enough")
elif not ("[A-Z]"):
  print("Passsword isn't strong enough")
elif not ("[0-9]"):
  print("Password isn't strong enough")
else:
  print("Password is strong enough")

Tags: 用户程序密码if字母not数字password
2条回答

您可以使用正则表达式简单地执行此操作,它将很好地工作:

import re
password = input("Input your password: ")

if (re.match(r"^.*[A-Z]", password) and re.match(r"^.*[0-9]", password) and len(password)>7 and re.match(r"^.*[a-z]", password) ):   
    print("Password is strong enough")
else:
    print("Password is not strong enough")

此支票:

elif not ("[a-z]"):

什么都不做;它只是检查静态字符串的真值。因为"[a-z]"是一个非空字符串,所以它总是被认为是true(或“truthy”),这意味着无论password中有什么内容not "[a-z]"总是False。您可能想使用re模块,您可以在这里阅读:https://docs.python.org/3/library/re.html

下面是一种不使用正则表达式实现此检查的方法,使用Python的allany函数、其in关键字和string模块,该模块包含方便的字符串,如ascii_lowercase(所有小写字母,对应于正则表达式字符类[a-z]):

import string

password = input("Input your password: ")

if all([
    len(password) >= 8,
    any(c in password for c in string.ascii_lowercase),
    any(c in password for c in string.ascii_uppercase),
    any(c in password for c in string.digits),
]):
    print("Password is strong enough")
else:
    print("Password is not strong enough")

相关问题 更多 >