I have been observing unusual behavior with the .islower()
and .isupper()
methods in Python. For example:
>>> test = '8765iouy9987OIUY'
>>> test.islower()
False
>>> test.isupper()
False
However, the following mixed string value seems to work:
>>> test2 = 'b1'
>>> test2.islower()
True
>>> test2.isupper()
False
I do not understand this anomaly. How can I detect lower case letters as in test
?
islower()
and isupper()
only return True
if all letters in the string are lowercase or uppercase, respectively.
You'd have to test for individual characters; any()
and a generator expression makes that relatively efficient:
>>> test = '8765iouy9987OIUY'
>>> any(c.islower() for c in test)
True
>>> any(c.isupper() for c in test)
True
From the documentation:
islower() Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise.
isupper() Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise.
To be more clear, both "1".islower()
and "1".isupper()
return False
. If there is no cased letter, both function return false.
If you want to remove all the lowercase letters, you could:
>>> test = '8765iouy9987OIUY'
>>> "".join([i for i in test if not i.islower()])
'87659987OIUY'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With