Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if lowercase letters exist?

Tags:

python

string

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?

like image 925
Borealis Avatar asked Apr 10 '14 19:04

Borealis


2 Answers

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
like image 95
Martijn Pieters Avatar answered Oct 10 '22 04:10

Martijn Pieters


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'
like image 23
Sheng Avatar answered Oct 10 '22 03:10

Sheng