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!
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'