In this tutorial, we will learn how to check if a string has an uppercase letter using Python. This is a useful skill to have as it can help you validate user input, format text, and analyze data.
Step 1: Understanding the isupper() method
Python provides a built-in method called isupper()
that checks if all the characters in a string are uppercase letters. If all the characters in a string are uppercase letters, it returns True
; otherwise, it returns False
. For example:
1 2 3 4 5 |
s = "HELLO" print(s.isupper()) # Output: True s1 = "Hello" print(s1.isupper()) # Output: False |
However, this method does not allow us to check if a string contains at least one uppercase letter. We need to create our own function for this task.
Step 2: Creating a function to check for uppercase letters
Let’s create a function called has_uppercase_letter()
that takes a string as an argument and returns True
if at least one uppercase letter is present in the string; otherwise, it returns False
.
To achieve this, we will use a for loop to iterate through each character in the string and check if it is an uppercase letter using the isupper()
method. If we find an uppercase letter, we will return True
.
If the loop completes without finding any uppercase letters, we will return False
.
The function will look like this:
1 2 3 4 5 |
def has_uppercase_letter(s: str) -> bool: for char in s: if char.isupper(): return True return False |
Step 3: Using the function to check a string
Now that we have our function, let’s use it to check a few strings to see if they contain uppercase letters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def has_uppercase_letter(s: str) -> bool: for char in s: if char.isupper(): return True return False s1 = "Hello, world!" s2 = "hello, world!" s3 = "12345" s4 = "=!@#$%^&*()" print(has_uppercase_letter(s1)) # Output: True print(has_uppercase_letter(s2)) # Output: False print(has_uppercase_letter(s3)) # Output: False print(has_uppercase_letter(s4)) # Output: False |
Output:
True False False False
As you can see, our function correctly identifies when a string contains an uppercase letter.
Conclusion
In this tutorial, we have learned how to check if a string has an uppercase letter using Python.
We created a custom function called has_uppercase_letter()
that iterates through each character in the input string and checks if it’s an uppercase letter using the built-in isupper()
method.
This function can be particularly useful when validating user input, formatting text, or analyzing data.