我正在尝试向用户请求密码,我可以验证长度,但我不知道如何在他们的密码中请求大写字母。
您可以与string.ascii_uppercase
:中的字母进行set
交集
import string
def validate(pw):
return len(pw) >= 8 and set(string.ascii_uppercase).intersection(pw)
该代码返回集合,如果该集合不为空(即密码至少包含一个大写ASCII字母),则该集合将是真实的。您可能还需要测试小写字母,这可以通过另一个集合交集来完成,这次是通过string.ascii_lowercase
构建的集合。
可能最简单的方法是查看密码是否在小写时更改:
if password.lower() == password:
print('Password rejected - needs a capital letter!')
您也可以使用regex(以防您还没有遇到足够的问题):
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.')
遍历字符串并检查是否有任何字符是大写
def checkCapital(password):
for x in password:
if 'A'<=x<='Z':
return True
return False