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.
Asked
Active
Viewed 498 times
3 Answers
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
-
This works but isn't as explicit as checking for `x.isupper()`, in my opinion. – Chris L. Barnes Dec 04 '15 at 17:26
-
Using list comprehension, you could do `[x for x in password if x.isupper()]`. That gives you a list of characters that are uppercase and is falsy if there are no uppercase characters. – jcasner Jul 20 '17 at 18:07
-
The more idiomatic form of this would be `return any(c.isupper() for c in password)` – Chris L. Barnes Oct 29 '18 at 18:16