【问题标题】:Checking password input for integers, capitals and lowercase?检查整数、大写和小写的密码输入?
【发布时间】:2014-10-15 15:45:51
【问题描述】:

我正在为学校的计算机课做一些工作,我们需要输入密码。输入需要在 6 到 12 个字符之间,并且包含大写、小写和数字。到目前为止我有这个:

import sys
import os
def checkPass():
    passLoop = True
    while passLoop:
        print("Welcome user!")
        x = len(input("Please enter your password, between 6 and 12 characters. "))
        if x < 6:
            print("Your password is too short")
            r = input("Please press any key to restart the program")
        elif x > 12:
            print("Your password is too long")
            r = input("Please press any key to restart the program")
        else:
            print("Thank you for entering your password.")
            print("Your password is strong. Thank you for entering!")
            passLoop = False

checkPass()

我需要您的帮助来检查大写、小写和整数。我还年轻所以请不要太苛刻!

【问题讨论】:

  • 提示:将密码本身存储在某个变量中。现在你只存储长度。
  • 不幸的是,这不是 stackoverflow 的工作方式。我们可以帮助您解决您遇到的一些具体问题,但我们不会为您完成作业。
  • 如果我完成了 x = password ?
  • 对不起,本杰明,这不是我要问的!我只是在询问有关检查强度的提示,例如凯文所说的!

标签: python


【解决方案1】:
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?\d).{6,12}$

你可以试试这个。这里使用re

你可以像这样使用它

import re
if re.match(r"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?\d).{6,12}$",pass,re.M):
        print "valid"
else:
        print "invalid"

查看演示。

http://regex101.com/r/dZ1vT6/28

【讨论】:

  • 这个正则表达式很酷,但它非常难以维护,对初学者来说更不友好。
  • 这个和这个r'^[a-zA-Z0-9]{6,12}$'一样吗
  • @vks,我看到我重新阅读了 OP 问题,它需要包含所有的上、下和 0-9
  • @Anzel 尝试演示。在那里尝试各种输入。
【解决方案2】:

假设您将密码存储在名为 passwd 的变量中。 然后我们可以接受您的字面要求并为它们写检查:

输入需要在 6 到 12 个字符之间,

if not 6 <= len(passwd) <= 12: ...

并包含大写,

if not any(c.isupper() for c in passwd): ...

小写

if not any(c.islower() for c in passwd): ...

和里面的数字。

if not any(c.isdigit() for c in passwd): ...

附带说明:您确实不应该限制密码的长度。

【讨论】:

    【解决方案3】:

    any 函数与地图结合使用会很有帮助。 map 函数遍历给定字符串的所有字符,并通过给定的 lambda 函数测试字符是否为大写。由 map 函数的第一个 true 时返回 true 的 any 函数使用

     >>> any(map(lambda a:a.isupper(),"aba"))
     False
     >>> any(map(lambda a:a.isupper(),"aBa"))
     True
    

    你可以把它包装成一个单独的函数,比如

    >>> def test(passwd,func):
            return any(map(func,passwd))
    
    >>> test("aBa",str.isupper)
        True
    >>> test("ab0",str.isdigit)
        True
    >>> test("aBa",str.islower)
        True
    

    【讨论】:

      猜你喜欢
      • 2016-03-02
      • 2021-03-13
      • 1970-01-01
      • 2013-12-07
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      相关资源
      最近更新 更多