我一直在观察不寻常的行为.islower()和.isupper()Python中的方法.例如:
>>> test = '8765iouy9987OIUY'
>>> test.islower()
False
>>> test.isupper()
False
Run Code Online (Sandbox Code Playgroud)
但是,以下混合字符串值似乎工作:
>>> test2 = 'b1'
>>> test2.islower()
True
>>> test2.isupper()
False
Run Code Online (Sandbox Code Playgroud)
我不明白这种异常现象.如何检测小写字母test?
Mar*_*ers 12
islower()并且isupper()只返回True,如果所有的字符串中的字母是大写还是小写,分别.
你必须测试个别角色; any()并且生成器表达式使其相对有效:
>>> test = '8765iouy9987OIUY'
>>> any(c.islower() for c in test)
True
>>> any(c.isupper() for c in test)
True
Run Code Online (Sandbox Code Playgroud)
从文档:
islower()如果字符串中的所有外壳字符都是小写且至少有一个外壳字符,则返回true,否则返回false.
isupper()如果字符串中的所有外壳字符都是大写且至少有一个外壳字符,则返回true,否则返回false.
为了更加清晰,双方"1".islower()并"1".isupper()返回False.如果没有套装字母,则两个函数都返回false.
如果要删除所有小写字母,您可以:
>>> test = '8765iouy9987OIUY'
>>> "".join([i for i in test if not i.islower()])
'87659987OIUY'
Run Code Online (Sandbox Code Playgroud)
你可以使用re模块:
import re
print re.findall(r"[a-z]",'8765iouy9987OIUY')
Run Code Online (Sandbox Code Playgroud)
输出:
['i', 'o', 'u', 'y']
Run Code Online (Sandbox Code Playgroud)
如果没有匹配,您将获得[]输出.正则表达式匹配从a到z的所有字符.