Python 3 – String isupper() Method
The isupper() method in Python 3 is used to check whether all the characters in a string are uppercase or not. When we say all the characters, it means the string should not contain any non-alphabetic character or whitespace character. If the string contains any non-alphabetic or whitespace character, the isupper() method will return False.
Here is the basic syntax of the isupper() method:
string.isupper()
The above method will return True if all the characters in the string are in uppercase, otherwise, it will return False.
Let’s take a few examples to understand the working of the isupper() method.
# Example 1
string1 = "HELLO WORLD"
print(string1.isupper()) # True
# Example 2
string2 = "Hello World"
print(string2.isupper()) # False
# Example 3
string3 = "12345"
print(string3.isupper()) # False
# Example 4
string4 = "HELLO WORLD!!!"
print(string4.isupper()) # True
In Example 1, all the characters in the string string1
are in uppercase, so the isupper() method will return True.
In Example 2, the string string2
contains alphabetic characters in both uppercase and lowercase, so the isupper() method will return False.
In Example 3, the string string3
contains only non-alphabetic characters, so the isupper() method will return False.
In Example 4, the string string4
contains alphabetic characters in uppercase and non-alphabetic characters, but still, the isupper() method will return True because it is not checking for non-alphabetic characters.
Using isupper() method with user input
Now, let’s take an example to see how we can use isupper() method with user input.
input_str = input("Enter any string: ")
print(input_str.isupper())
In the above example, we are taking input from the user and then using the isupper() method to check whether the string entered by a user is all in uppercase or not.
Here is the sample output for this example:
Enter any string: PYTHON IS AWESOME
True
Using isupper() method with slicing
We can also use the isupper() method with slicing to check whether all the characters in a particular range are in uppercase or not.
string = "HELLO WORLD!!!"
print(string[0:5].isupper()) # True
print(string[6:11].isupper()) # True
print(string[12:].isupper()) # True
In the above example, we are checking whether characters in the first five characters, next five characters, and after the 12th position are all in uppercase or not.
Conclusion
The isupper() method is a very handy method in Python 3 to check whether all the characters in a string are in uppercase or not. It can be used with user inputs, slicing, or hardcoded strings. It is very helpful when dealing with uppercase strings in Python 3.