[python] How to detect lowercase letters in Python?

I need to know if there is a function that detects the lowercase letters in a string. Say I started writing this program:

s = input('Type a word')

Would there be a function that lets me detect a lowercase letter within the string s? Possibly ending up with assigning those letters to a different variable, or just printing the lowercase letters or number of lowercase letters.

While those would be what I would like to do with it I'm most interested in how to detect the presence of lowercase letters. The simplest methods would be welcome, I am only in an introductory python course so my teacher wouldn't want to see complex solutions when I take my midterm. Thanks for the help!

This question is related to python string lowercase letters

The answer is


You should use raw_input to take a string input. then use islower method of str object.

s = raw_input('Type a word')
l = []
for c in s.strip():
    if c.islower():
        print c
        l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)

Just do -

dir(s)

and you will find islower and other attributes of str


import re
s = raw_input('Type a word: ')
slower=''.join(re.findall(r'[a-z]',s))
supper=''.join(re.findall(r'[A-Z]',s))
print slower, supper

Prints:

Type a word: A Title of a Book
itleofaook ATB

Or you can use a list comprehension / generator expression:

slower=''.join(c for c in s if c.islower())
supper=''.join(c for c in s if c.isupper())
print slower, supper

Prints:

Type a word: A Title of a Book
itleofaook ATB

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() == c
    True
    
  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_lowercase
    True
    

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

If you don't want to use the libraries and want simple answer then the code is given below:

  def swap_alpha(test_string):
      new_string = ""
      for i in test_string:
          if i.upper() in test_string:
              new_string += i.lower()

          elif i.lower():
                new_string += i.upper()

          else:
              return "invalid "

      return new_string


user_string = input("enter the string:")
updated = swap_alpha(user_string)
print(updated)

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 re
    
    lc = 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']

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to lowercase

Ignoring upper case and lower case in Java how to convert Lower case letters to upper case letters & and upper case letters to lower case letters How to detect lowercase letters in Python? .toLowerCase not working, replacement function? How to convert a string from uppercase to lowercase in Bash? How to convert array values to lowercase in PHP? Java Program to test if a character is uppercase/lowercase/number/vowel How do I lowercase a string in Python? How do I lowercase a string in C? How to convert a string to lower case in Bash?

Examples related to letters

How to detect lowercase letters in Python?