python 我的密码强度检查程序可以减少吗

v09wglhw  于 2024-01-05  发布在  Python
关注(0)|答案(2)|浏览(191)

我做了一个密码强度检查器。
代码:

  1. import re
  2. upper = re.compile(r'[A-Z]')
  3. lower = re.compile(r'[a-z]')
  4. digit = re.compile(r'[0-9]')
  5. special_char = re.compile(r'[~!@#$%^&*()]')
  6. # text = 'd3F#$%^&232sdsGDFD'
  7. text = input("Enter a password to check it's strength\n")
  8. digit_check = digit.search(text)
  9. upper_check = upper.search(text)
  10. lower_check = lower.search(text)
  11. special_char_chk = special_char.search(text)
  12. if digit_check and upper_check and lower_check and special_char_chk and len(text)>=8:
  13. print("Valid password\nPassword is:" + text)
  14. else:
  15. print("Invalid")

字符串
我试着让它在我的水平短。
我可以在多大程度上减少代码行数?

bkkx9g8r

bkkx9g8r1#

更短!=更好。但是,是的,它可以变得更短更好,例如:

  1. if (all(re.search(p, text) for p in ['[A-Z]', '[a-z]', '[0-9]', '[~!@#$%^&*()]']) and
  2. len(text) >= 8):

字符串

ctehm74n

ctehm74n2#

你完全可以将这些表达式合并组合成一个正则表达式:

  1. expr = re.compile('(^[^A-Z]$)|(^[^a-z]$)|(^[^0-9]$)|(^[^~!@#$%^&*()]$)|(^.{0,7}$)')
  2. if expr.search('a99@999B'):
  3. print('Invalid')
  4. else:
  5. print('Valid')

字符串
请注意,表达式中的布尔值是使用公式a & b = !a | !b组合的。所以基本上,这是在寻找:

  1. if(no_lowercase or no_uppercase or no_digit or no_symbol or 7chars_or_fewer):
  2. #it's invalid
  3. else:
  4. #it's valid

展开查看全部

相关问题