1

I am trying to ask the user for a password, I can validate the length but I don't know how to ask for a capital letter in their password.

Peapay
  • 29
  • 2

3 Answers3

3

Probably the easiest way to do it is to see whether the password changes when you make it all lower case:

if password.lower() == password:
    print('Password rejected - needs a capital letter!')

You could also do it with regex (in case you didn't have enough problems already):

import re
# if you're just looking at one at a time
if not re.search('[A-Z]', password):
    print('Password rejected etc.')

# if you're probably looking at many
regex = re.compile('[A-Z]')
if not regex.search(password):
    print('Password rejected etc.')
Chris L. Barnes
  • 475
  • 4
  • 13
3

You could do a set intersection with the letters in string.ascii_uppercase:

import string

def validate(pw):
    return len(pw) >= 8 and set(string.ascii_uppercase).intersection(pw)

That code returns the set, which will be truthy if it is not empty (that is, the password contained at least one uppercase ASCII letter). You may also need to test for lowercase letters, which you can do with another set intersection, this time with a set built from string.ascii_lowercase.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
1

Iterate over the string and check if any character is uppercase

def checkCapital(password):
    for x in password:
        if 'A'<=x<='Z':
            return True
    return False
Saeid
  • 4,147
  • 7
  • 27
  • 43