How to detect lowercase letters in Python? How to detect lowercase letters in Python? python python

How to detect lowercase letters in Python?


To check if a character is lower case, use the islower method of str. This simple imperative program prints all the lowercase letters in your string:

for c in s:    if c.islower():         print c

Note that in Python 3 you should use print(c) instead of print c.


Possibly ending up with assigning those letters to a different variable.

To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:

>>> s = 'abCd'>>> lowercase_letters = [c for c in s if c.islower()]>>> print lowercase_letters['a', 'b', 'd']

Or to get a string you can use ''.join with a generator:

>>> lowercase_letters = ''.join(c for c in s if c.islower())>>> print lowercase_letters'abd'


There are 2 different ways you can look for lowercase characters:

  1. Use str.islower() to find lowercase characters. Combined with a list comprehension, you can gather all lowercase letters:

    lowercase = [c for c in s if c.islower()]
  2. You could use a regular expression:

    import relc = re.compile('[a-z]+')lowercase = lc.findall(s)

The first method returns a list of individual characters, the second returns a list of character groups:

>>> import re>>> lc = re.compile('[a-z]+')>>> lc.findall('AbcDeif')['bc', 'eif']


There are many methods to this, here are some of them:

  1. Using the predefined str method islower():

    >>> c = 'a'>>> c.islower()True
  2. Using the ord() function to check whether the ASCII code of the letter is in the range of the ASCII codes of the lowercase characters:

    >>> c = 'a'>>> ord(c) in range(97, 123)True
  3. Checking if the letter is equal to it's lowercase form:

    >>> c = 'a'>>> c.lower() == cTrue
  4. Checking if the letter is in the list ascii_lowercase of the string module:

    >>> from string import ascii_lowercase>>> c = 'a'>>> c in ascii_lowercaseTrue

But that may not be all, you can find your own ways if you don't like these ones: D.

Finally, let's start detecting:

d = str(input('enter a string : '))lowers = [c for c in d if c.islower()]# here i used islower() because it's the shortest and most-reliable# one (being a predefined function), using this list comprehension# is (probably) the most efficient way of doing this