In this tutorial, we’ll learn how to use the isupper() function in Python. This function is part of the string methods and checks whether all the characters in a given string are uppercase or not, returning a True
or False
value accordingly.
Step 1: Understanding the isupper() function
The isupper() function in Python is a built-in method that is applied to string objects. It returns True
if all the characters within the string are uppercase, else it returns False
. Let’s have a look at the basic syntax for isupper().
1 |
string.isupper() |
Here, the string
is any valid Python string that we want to check for uppercase characters.
For example, let’s try some basic examples:
1 2 3 |
print('HELLO WORLD'.isupper()) # Output: True print('Hello World'.isupper()) # Output: False print('123'.isupper()) # Output: False |
Note that it only returns True
if all the characters within the string are uppercase. If the string contains special characters, numbers or lowercase letters, it will return False
.
Step 2: Using isupper() in conditional statements
isupper() can often be used in conditional statements to filter out strings that only have uppercase characters from a list or to process them differently. Let’s take a look at an example.
Suppose you have a list of strings, and you want to filter out only the strings that have all uppercase characters. You could use a for
loop with an if
statement using the isupper() method, as shown below:
1 2 3 4 5 6 7 8 |
str_list = ['HELLO', 'WORLD', 'Python', '123'] uppercase_str_list = [] for string in str_list: if string.isupper(): uppercase_str_list.append(string) print(uppercase_str_list) # Output: ['HELLO', 'WORLD'] |
Here, we loop through each string of the list and use the isupper()
function to check whether the string is all uppercase or not. If it is, we append it to our uppercase_str_list
.
Step 3: Using isupper() with list comprehensions
We can also use the isupper() function with list comprehensions, providing a shorter and more readable way to filter uppercase strings. Here’s how to rewrite the previous example using list comprehension:
1 2 3 4 |
str_list = ['HELLO', 'WORLD', 'Python', '123'] uppercase_str_list = [string for string in str_list if string.isupper()] print(uppercase_str_list) # Output: ['HELLO', 'WORLD'] |
With a list comprehension, we can achieve the same result with just one line of code.
Full code example
1 2 3 4 |
str_list = ['HELLO', 'WORLD', 'Python', '123'] uppercase_str_list = [string for string in str_list if string.isupper()] print(uppercase_str_list) # Output: ['HELLO', 'WORLD'] |
Conclusion
The isupper() function is a useful and easy-to-understand method to determine if all characters in a given string are uppercase letters. It helps in filtering and identifying uppercase strings from a list, and can be used both in conditional statements as well as list comprehensions.
Now you can easily perform string operations based on uppercase characters with the help of isupper() in Python.