Validation of a Password - Python

前端 未结 11 1990
自闭症患者
自闭症患者 2020-11-27 08:20

So I have to create code that validate whether a password:

  • Is at least 8 characters long
  • Contains at least 1 number
  • Contains at least 1
11条回答
  •  孤独总比滥情好
    2020-11-27 08:40

    ''' Minimum length is 5;
     - Maximum length is 10;
     - Should contain at least one number;
     - Should contain at least one special character (such as &, +, @, $, #, %, etc.);
     - Should not contain spaces.
    '''
    
    import string
    
    def checkPassword(inputStr):
        if not len(inputStr):
            print("Empty string was entered!")
            exit(0)
    
        else:
            print("Input:","\"",inputStr,"\"")
    
        if len(inputStr) < 5 or len(inputStr) > 10:
            return False
    
        countLetters = 0
        countDigits = 0
        countSpec = 0
        countWS = 0
    
        for i in inputStr:
            if i in string.ascii_uppercase or i in string.ascii_lowercase:
                 countLetters += 1
            if i in string.digits:
                countDigits += 1
            if i in string.punctuation:
                countSpec += 1
            if i in string.whitespace:
                countWS += 1
    
        if not countLetters:
            return False
        elif not countDigits:
            return False
        elif not countSpec:
            return False
        elif countWS:
            return False
        else:
            return True
    
    
    print("Output: ",checkPassword(input()))
    

    With Regex

    s = input("INPUT: ")
    print("{}\n{}".format(s, 5 <= len(s) <= 10 and any(l in "0123456789" for l in s) and any(l in "!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~" for l in s) and not " " in s))
    

    Module import

    from string import digits, punctuation
    
    def validate_password(p):
        if not 5 <= len(p) <= 10:
            return False
    
        if not any(c in digits for c in p):
            return False
    
        if not any(c in punctuation for c in p):
            return False
    
        if ' ' in p:
            return False
    
        return True
    
    for p in ('DJjkdklkl', 'John Doe'
    , '$kldfjfd9'):
        print(p, ': ', ('invalid', 'valid')[validate_password(p)], sep='')
    

提交回复
热议问题