Python if语句检查字符串是否有大写字母、小写字母和数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17140408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If statement to check whether a string has a capital letter, a lower case letter and a number
提问by AmaChurLOL
Can someone give an idea on how to test a string that:
有人可以提供有关如何测试字符串的想法:
- contains at least one upper case letter
- contains at least one lower case letter
- contains at least one number
- has a minimal length of 7 characters
- 包含至少一个大写字母
- 包含至少一个小写字母
- 包含至少一个数字
- 最小长度为 7 个字符
采纳答案by John La Rooy
if (any(x.isupper() for x in s) and any(x.islower() for x in s)
and any(x.isdigit() for x in s) and len(s) >= 7):
Another way is to express your rules as a list of (lambda) functions
另一种方法是将您的规则表示为 (lambda) 函数列表
rules = [lambda s: any(x.isupper() for x in s), # must have at least one uppercase
lambda s: any(x.islower() for x in s), # must have at least one lowercase
lambda s: any(x.isdigit() for x in s), # must have at least one digit
lambda s: len(s) >= 7 # must be at least 7 characters
]
if all(rule(s) for rule in rules):
...
Regarding your comment. To build an error message
关于你的评论。构建错误消息
errors = []
if not any(x.isupper() for x in password):
errors.append('Your password needs at least 1 capital.')
if not any(x.islower() for x in password):
errors.append(...)
...
if errors:
print " ".join(errors)
回答by FMc
import re
s = 'fooBar3'
rgx = re.compile(r'\d.*?[A-Z].*?[a-z]')
if rgx.match(''.join(sorted(s))) and len(s) >= 7:
print 'ok'
Even more fun is this regex, which will report the type of character that is missing:
更有趣的是这个正则表达式,它将报告缺少的字符类型:
s = 'fooBar'
rules = [
r'(?P<digit>\d)?',
r'(?P<upper>[A-Z])?',
r'(?P<lower>[a-z])?',
]
rgx = re.compile(r'.*?'.join(rules))
checks = rgx.match(''.join(sorted(s))).groupdict()
problems = [k for k,v in checks.iteritems() if v is None]
print checks # {'upper': 'B', 'digit': None, 'lower': 'a'}
print problems # ['digit']
Finally, here's a variant of the excellent rules-based approach suggested by gnibbler.
最后,这里是 gnibbler 建议的基于规则的优秀方法的一个变体。
s = 'fooBar'
rules = [
lambda s: any(x.isupper() for x in s) or 'upper',
lambda s: any(x.islower() for x in s) or 'lower',
lambda s: any(x.isdigit() for x in s) or 'digit',
lambda s: len(s) >= 7 or 'length',
]
problems = [p for p in [r(s) for r in rules] if p != True]
print problems # ['digit', 'length']

