To check if a string contains only uppercase characters in Python, the built-in string method isupper() can be utilized. This method returns True if all the characters in the string are uppercase letters and there is at least one character in the string. If the string is empty or contains any lowercase letters, digits, or special characters, it returns False.
Here is how you can use it:
# Example string
my_string = "HELLO"
# Checking if the string contains only uppercase letters
if my_string.isupper():
print("The string contains only uppercase characters.")
else:
print("The string does not contain only uppercase characters.")
Case Scenarios
1. String with Only Uppercase Letters
string1 = "WORLD"
print(string1.isupper()) # Output: True
2. String with Mixed Case
string2 = "Hello"
print(string2.isupper()) # Output: False
3. String with Lowercase Letters
string3 = "hello"
print(string3.isupper()) # Output: False
4. String with Digits or Special Characters
string4 = "HELLO123"
print(string4.isupper()) # Output: False
string5 = "HELLO!"
print(string5.isupper()) # Output: False
5. Empty String
string6 = ""
print(string6.isupper()) # Output: False
By employing the isupper() method, it becomes straightforward to determine the case sensitivity of the characters within a string, making it an effective tool in various string validation scenarios in Python programming.