Use isupper() Method
In this step, you will learn how to use the isupper()
method in Python to check if a string is entirely in uppercase. The isupper()
method is a built-in string method that returns True
if all characters in the string are uppercase, and False
otherwise.
Let's modify the uppercase_strings.py
file you created in the previous step to use the isupper()
method.
- Open the
uppercase_strings.py
file in the VS Code editor.
- Modify the code to include the
isupper()
method as follows:
## Example strings
string1 = "HELLO"
string2 = "Hello"
string3 = "123HELLO"
string4 = "HELLO WORLD"
## Check if the strings are uppercase using isupper()
result1 = string1.isupper()
result2 = string2.isupper()
result3 = string3.isupper()
result4 = string4.isupper()
## Print the results
print(f"String 1: {string1}, is uppercase: {result1}")
print(f"String 2: {string2}, is uppercase: {result2}")
print(f"String 3: {string3}, is uppercase: {result3}")
print(f"String 4: {string4}, is uppercase: {result4}")
In this code, we are calling the isupper()
method on each of the example strings and storing the results in variables result1
, result2
, result3
, and result4
. Then, we print the original strings along with their corresponding isupper()
results.
Now, let's run the script to see the output.
- Open a terminal in the VS Code environment.
- Execute the Python script using the following command:
python uppercase_strings.py
You should see the following output:
String 1: HELLO, is uppercase: True
String 2: Hello, is uppercase: False
String 3: 123HELLO, is uppercase: False
String 4: HELLO WORLD, is uppercase: False
As you can see, string1
(HELLO) is the only string that returns True
because all its characters are uppercase. The other strings return False
because they contain lowercase characters, numbers, or spaces.
In the next step, you will learn how to account for non-letter characters when checking for uppercase strings.