Skip to main content

How to check if a string is uppercase in Python

How to check if a string is uppercase in Python.

Here is a step-by-step tutorial on how to check if a string is uppercase in Python.

  1. Start by defining a string variable that you want to check for uppercase. For example, let's say we have a string variable named my_string.
   my_string = "HELLO"
  1. Use the isupper() function to check if the string is entirely in uppercase. This function returns True if all characters in the string are uppercase, and False otherwise.
   is_uppercase = my_string.isupper()

In this case, is_uppercase will be True since all characters in the string are uppercase.

  1. To handle cases where the string might contain whitespace or non-alphabetic characters, you can use the isalpha() function to ensure that the string contains only alphabetic characters before checking for uppercase.
   if my_string.isalpha() and my_string.isupper():
print("The string is uppercase.")
else:
print("The string is not entirely in uppercase.")

This will output "The string is uppercase" since my_string is entirely in uppercase.

  1. If you want to check if a string is uppercase without considering the original case of the characters, you can convert the string to uppercase using the upper() function and then compare it with the original string.
   if my_string.upper() == my_string:
print("The string is uppercase.")
else:
print("The string is not entirely in uppercase.")

This approach will also output "The string is uppercase" for my_string since the uppercase version of the string is equal to the original string.

That's it! You have now learned how to check if a string is uppercase in Python.