In this tutorial, we will discuss how to check if a string is all uppercase in Python. This can be useful when you need to validate user input or analyze text. Python has many built-in functions that can be used for string manipulations, like checking if a given string is all in uppercase.
Step 1: Using the isupper() Method
The easiest way to check if a given string is all in uppercase is by using the built-in isupper() method. This method returns True if all the characters in the given string are uppercase, otherwise, it returns False.
Here’s an example:
1 2 3 4 5 6 7 8 |
def is_uppercase(string): return string.isupper() test_string1 = "HELLO16WORLD" test_string2 = "Hello World" print(is_uppercase(test_string1)) # Output: True print(is_uppercase(test_string2)) # Output: False |
Step 2: Using a Custom Function
You can also write a custom function to check if a string is all uppercase. In this approach, you loop through the characters of the string and check if each character is an uppercase character.
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 |
def is_uppercase(string): for char in string: if char.isalpha() and not char.isupper(): return False return True test_string1 = "HELLO16WORLD" test_string2 = "Hello World" print(is_uppercase(test_string1)) # Output: True print(is_uppercase(test_string2)) # Output: False |
In this example, we use the isalpha() and isupper() methods to check if a character is an uppercase letter. If the character is an uppercase letter, we continue to check the next character. If a non-uppercase letter is found, the function returns False.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def is_uppercase(string): return string.isupper() test_string1 = "HELLO16WORLD" test_string2 = "Hello World" print(is_uppercase(test_string1)) print(is_uppercase(test_string2)) def is_uppercase_custom(string): for char in string: if char.isalpha() and not char.isupper(): return False return True test_string1 = "HELLO16WORLD" test_string2 = "Hello World" print(is_uppercase_custom(test_string1)) print(is_uppercase_custom(test_string2)) |
Output:
True False True False
Conclusion
In this tutorial, we discussed two different ways to check if a string is all uppercase in Python.
The first method using the built-in isupper() method is the most straightforward and recommended approach. The second approach, creating a custom function, can be used when you need more control over the process.
Both methods are valid and can help you easily determine if a given string is all uppercase.