This article will discuss different ways to check if a given string is lowercase or not in Python.
Table Of Contents
Check if String is Lowercase using islower()
In Python, the string class provides a member function islower(). It returns True if all the alphabetic characters in the string are lowercase; otherwise, it returns False. Let’s use this to check if a string is lowercase or not,
Example 1:
sample_str = 'this is a sample string' # Check If String contains all lowercase letters if sample_str.islower(): print("String is a lowercase string") else: print("String is not a lowercase string")
Output:
String is a lowercase string
In this case, the given string does not contain any uppercase character.
Example 2:
Frequently Asked:
sample_str = 'will meet you Some Other Day' # Check If String contains all lowercase letters if sample_str.islower(): print("String is a lowercase string") else: print("String is not a lowercase string")
Output:
String is not a lowercase string
It was a negative test, given string is not lowercase because it has a few uppercase characters.
Check if String is Lowercase using regex
The regex module of Python provides a function regex.search(pattern, string). It accepts a regex pattern and a string as arguments. When called, it looks through the string for a match to the given regex pattern and returns a Match object in case a match is found, or None if no match was found.
We will use this function and check if all the alphabetic characters in the string are of lowercase. For this we will use the regex pattern “^[a-z\s\t]+$”. This pattern ensures that the string contains either lowercase letters or whitespaces. For example,
Example 1:
import re sample_str = 'this is a sample string' # Check if String is lowercase if re.search("^[a-z\s\t]+$", sample_str) is not None: print("String is a lowercase string") else: print("String is not a lowercase string")
Output:
String is a lowercase string
In this case, the given string does not contain any uppercase character.
Example 2:
import re sample_str = 'will meet you Some Other Day' # Check if String is lowercase if re.search("^[a-z\s\t]+$", sample_str) is not None: print("String is a lowercase string") else: print("String is not a lowercase string")
Output:
String is not a lowercase string
It was a negative test, given string is not lowercase because it has a few uppercase characters.
Summary:
We learned about two different ways to check if a string is lowercase or not in Python.