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.
islower() In Python, islower() is a built-in method used for string handling. The islower() method returns True if all characters in the string are lowercase, otherwise, returns “False”.
isLowerCase() method can be used to determine if a letter is a lowercase letter. This method takes a char as argument and return a boolean value. If it returns true it means the character is in lowercase form. And if it returns false it means the character is not in lowercase form.
The Python upper() method converts all lowercase letters in a string to uppercase and returns the modified string. The Python isupper() returns true if all of the characters in a string are uppercase, and false if they aren't.
Traverse the string character by character from start to end. Check the ASCII value of each character for the following conditions: If the ASCII value lies in the range of [65, 90], then it is an uppercase letter. If the ASCII value lies in the range of [97, 122], then it is a lowercase letter.
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:
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()]
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']
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