if语句检查字符串是否有大写字母,小写字母和数字

时间:2013-06-17 04:28:01

标签: python

有人可以就如何测试字符串提出一个想法:

  • 至少包含一个大写字母
  • 至少包含一个小写字母
  • 至少包含一个数字
  • 的最小长度为7个字符

2 个答案:

答案 0 :(得分:39)

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):

另一种方法是将您的规则表示为(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):
    ...

关于你的评论。构建错误消息

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)

答案 1 :(得分:7)

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'

这个正则表达式更有趣,它将报告缺少的字符类型:

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']

最后,这是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']