Python 如何检查是否存在小写字母?
我一直在观察Python中的.islower()和.isupper()方法的异常行为。例如:Python 如何检查是否存在小写字母?,python,string,Python,String,我一直在观察Python中的.islower()和.isupper()方法的异常行为。例如: >>> test = '8765iouy9987OIUY' >>> test.islower() False >>> test.isupper() False 但是,以下混合字符串值似乎有效: >>> test2 = 'b1' >>> test2.islower() True >>> test2
>>> test = '8765iouy9987OIUY'
>>> test.islower()
False
>>> test.isupper()
False
但是,以下混合字符串值似乎有效:
>>> test2 = 'b1'
>>> test2.islower()
True
>>> test2.isupper()
False
我不理解这种反常现象。如何检测测试中的小写字母?来自:
岛民()
如果字符串中所有大小写字符都是小写且至少有一个大小写字符,则返回true,否则返回false
isupper()
如果字符串中所有大小写字符均为大写且至少有一个大小写字符,则返回true,否则返回false
更清楚地说,islower()和isupper()返回False
。如果没有大小写字母,两个函数都返回false
如果要删除所有小写字母,可以:
>>> test = '8765iouy9987OIUY'
>>> "".join([i for i in test if not i.islower()])
'87659987OIUY'
islower()
和isupper()
仅返回True
如果字符串中的所有字母分别为小写或大写
你必须测试单个字符any()
和生成器表达式使其相对高效:
>>> test = '8765iouy9987OIUY'
>>> any(c.islower() for c in test)
True
>>> any(c.isupper() for c in test)
True
您可以使用以下模块:
输出:
['i', 'o', 'u', 'y']
如果没有匹配项,您将获得[]
作为输出。正则表达式匹配从a到z的所有字符。或者您可以尝试map()
:
然后使用any()
检查是否有大写字母:
any(map(str.isupper, '8765iouy9987OIUY'))
# output: True
对于至少需要1个字符(大写、小写和数字)的密码策略。我认为这是最具可读性和最直接的方法
def password_gen():
while True:
password = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for n in range(12))
tests = {}
tests['upper'] = any(char.isupper() for char in password)
tests['lower'] = any(char.islower() for char in password)
tests['digit'] = any(char.isdigit() for char in password)
if all(tests.values()):
break
return password
这也可以按如下方式进行:
test='8765iouy9987OIUY'
print(test==test.upper())#返回False,因为有些字母很小
测试='222WW'
print(test==test.upper())#返回True,因为没有小字母
什么异常?测试既不高也不低,它是混合的。另一方面,test2只包含小写字母
any(map(str.isupper, '8765iouy9987OIUY'))
# output: True
def password_gen():
while True:
password = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for n in range(12))
tests = {}
tests['upper'] = any(char.isupper() for char in password)
tests['lower'] = any(char.islower() for char in password)
tests['digit'] = any(char.isdigit() for char in password)
if all(tests.values()):
break
return password