Check if String is Uppercase in Python

This article will discuss different ways to check if a given string is uppercase or not in Python.

Table Of Contents

Check if String is Uppercase using isupper()

In Python, the string class provides a member function isupper(). It returns True if all the alphabetic characters in the string are of uppercase; otherwise, it returns False. Let’s use this to check if a string is of uppercase or not,

Example 1:

sample_str = 'THIS IS THE LAST LINE'

# Check If String contains all uppercase letters
if sample_str.isupper():
    print("String is a uppercase string")
else:
    print("String is not a uppercase string")

Output:

Advertisements
String is a uppercase string

In this case, the given string does not contain any lowercase character.

Example 2:

sample_str = 'WILL MEET you SOON'

# Check If String contains all uppercase letters
if sample_str.isupper():
    print("String is a uppercase string")
else:
    print("String is not a uppercase string")

Output:

String is not a uppercase string

It was a negative test, given string is not uppercase because it has a few lowercase characters.

Check if String is Uppercase 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 match is found, or None if no match was found.

We will use this function and check if all the alphabets in the string are of uppercase. For this we will use the regex pattern “^[A-Z\s\t]+$”. This pattern confirms that the string contains either uppercase letters or whitespaces. Let’s see some examples,

Example 1:

import re

sample_str = 'THIS IS THE LAST LINE'

# Check if String is uppercase
if re.search("^[A-Z\s\t]+$", sample_str) is not None:
    print("String is a uppercase string")
else:
    print("String is not a uppercase string")

Output:

String is a uppercase string

In this case, the given string does not contain any lowercase character.

Example 2:

import re

sample_str = 'WILL MEET you SOON'

# Check if String is uppercase
if re.search("^[A-Z\s\t]+$", sample_str) is not None:
    print("String is a uppercase string")
else:
    print("String is not a uppercase string")

Output:

String is not a uppercase string

It was a negative test, given string is not uppercase because it has a few lowercase characters.

Summary:

We learned two different ways to check if a string is uppercase or not in Python.

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top