【问题标题】:Checking for upper/lower case and symbols and digits in a variable python检查变量python中的大写/小写以及符号和数字
【发布时间】:2017-11-21 20:43:33
【问题描述】:

我目前正在使用正则表达式分别检查它们,所以我更喜欢使用 re 的答案。

我用来分别查找它们的示例:

 if re.search(r'[A-Z]', userpass):
    score += 5

但是,我想检查变量是否具有所有参数(大写/小写以及符号和数字),因此使用 re.search 每次都会返回 true,因为它只会检查例如是否有一个数字但我想检查是否有数字、大小写和符号。我要检查的符号还有:!$%^&*()-_=+

还要澄清一下,我对 python 很陌生,所以除了基本的东西外,几乎所有东西对我来说都是新的,所以我使用正则表达式,因为我觉得它很简单

【问题讨论】:

  • 因此您要验证用户密码是否至少具有每种类型,无论顺序如何。这是正确的吗?
  • @hoefling 我还会使用 re.search 吗?我不想看有没有一位数字,我想看有没有一位数字,大写/小写和符号
  • @greg muelller 是的
  • @hoefling 的建议不引用符号,只引用字母数字字符,因此您可能需要更多
  • 啊,所以你想检查一个字符串是否至少有一个数字和至少一个小写字母和至少一个大写字母?所以例如1Az 有效,但 Az 无效?如果是,那么忘记我之前提到的正则表达式。

标签: python


【解决方案1】:

我认为它可能更适合为此使用正则表达式。相反,我只会使用all()any()

checks = [[chr(c) for c in range(97, 123)] + [chr(c) for c in range(65, 91)], list("!$%^&*()-_=+"), [str(i) for i in range(10)]]

if all(any(c in check for c in userpass) for check in checks):
    score += 5

【讨论】:

    【解决方案2】:

    没有正则表达式:

    cond1 = any(c.isalpha() for c in password)
    cond2 = any(c.isnumber() for c in password)
    cond3 = any(word in password for word in '!$%^&*()-_=+')
    valid = cond1 and cond2 and cond3
    

    【讨论】:

      【解决方案3】:

      对于非正则表达式解决方案,您可以使用以下内容:

      def check_userpass(userpass):
          has_lower = userpass.upper() != userpass
          has_upper = userpass.lower() != userpass
          has_number = any(ch.isdigit() for ch in userpass)
          has_symbol = any(ch in "!$%^&*()-_=+" for ch in userpass)
          return has_lower and has_upper and has_number and has_symbol
      

      【讨论】:

      • 那么,如果我想在他们的分数上加 10,如果这是真的,我会放什么?
      【解决方案4】:

      一种方法是只使用any 而不是正则表达式

      if any(c.isupper() for c in userpass) and any(c.islower() for c in userpass) and any(c.isdigit() for c in userpass) and any(c in '!$%^&*()-_=+' for c in userpass):
          ...
      

      但这可能会变得相当冗长。如果我们的检查是我们可以传递字符的函数,我们可以这样做

      def ispunc(c):
          return c in '!$%^&*()-_=+'
      
      criteria = (str.isupper, str.islower, str.isdigit, ispunc)
      
      if all(any(check(c) for c in userpass) for check in criteria):
         ...
      

      【讨论】:

        猜你喜欢
        • 2017-06-11
        • 2013-12-07
        • 1970-01-01
        • 1970-01-01
        • 2015-02-08
        • 2012-01-03
        • 2013-04-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多