【问题标题】:Check string without regex [closed]检查没有正则表达式的字符串[关闭]
【发布时间】:2020-03-16 09:07:47
【问题描述】:

我有一个不想使用正则表达式的场景。我有一串密码。我想检查条件,它应该包含字母、数字、大写字母、小写字母、特殊字符。如何在没有正则表达式的情况下实现这一点? 最快的方法是什么? 我已经列出了 a-z 和 A-Z 以及 0-9 和特殊字符。但是将所有东西都写在列表中是很费时间的。 谢谢!

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您可以使用any 检查密码中的任何字符是否在您描述的字符集中。然后将其包装在 all 中,以确保满足您的每一项要求。

import string

def validate_password(password):
    char_sets = {string.ascii_lowercase,
                 string.ascii_uppercase,
                 string.digits,
                 string.punctuation}
    return all(any(letter in char_set for letter in password) for char_set in char_sets)

例如

>>> validate_password('password')
False
>>> validate_password('Password1!')
True

【讨论】:

    【解决方案2】:

    您可以使用如下的一组测试:

    pw = 'Ab1!'
    has_alpha = any([x.isalpha() for x in pw])
    has_num = any([x.isdigit() for x in pw])
    has_upper = any([x.isupper() for x in pw])
    has_lower = any([x.islower() for x in pw])
    has_symbol = any([not x.isalnum() for x in pw])
    
    is_proper_pw = has_alpha and has_num and has_upper and has_lower and has_symbol
    

    【讨论】:

      【解决方案3】:

      也许是通过比较密码中字符的 ASCII 值?比如:

      pw = "Hello"
      
      # convert password to ASCII numbers
      pw_to_ascii = [int(ord(c)) for c in pw]
      
      # ASCII range for capital letters
      cap_range = range(65,90)
      
      # CHeck for capitals
      for c in cap_range:
          if c in pw_to_ascii:
              print("Contains capital.") # replace with your desired action
      

      您可以通过检查不同的范围来对特殊字符进行额外的检查。这是一种天真的方法,但可以完成工作。如果您想限制可能的字符,就像大多数密码一样(例如空格),您可以添加一个范围来专门检查这些字符。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多