Check if string is upper, lower, or mixed case in Python

I want to classify a list of strings in Python depending on whether they are lowercase, lowercase or mixed.

How can i do this?

+80
python string
Nov 22 '11 at 6:29
source share
2 answers

There are several is methods in the lines. islower() and isupper() should suit your needs:

 >>> 'hello'.islower() True >>> [m for m in dir(str) if m.startswith('is')] ['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper'] 

Here is an example of how to use these methods to classify a list of strings:

 >>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG'] >>> [word for word in words if word.islower()] ['quick', 'jumped', 'the'] >>> [word for word in words if word.isupper()] ['BROWN', 'OVER', 'DOG'] >>> [word for word in words if not word.islower() and not word.isupper()] ['The', 'Fox', 'Lazy'] 
+146
Nov 22 '11 at 6:31
source share

I want to thank you for using the re module for this. Especially in case of case sensitivity.

We use the re.IGNORECASE parameter when compiling a regular expression for use in production environments with large amounts of data.

 >>> import re >>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER'] >>> >>> >>> pattern = re.compile('is') >>> >>> [word for word in m if pattern.match(word)] ['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper'] 

However, always try to use the in operator to compare strings, as described in detail in this post.

faster re-match-or-ul

Also described in detail in one of the best books on the study of python with

idiomatic python

0
Jan 07 '19 at 16:51
source share



All Articles