To count the uppercase letters in a Python string, you can use a combination of the isupper()
string method and a loop to iterate over each character in the string. Here’s an example:
# Example string
my_string = "Hello World! How Are You?"
# Initialize a counter for uppercase letters
uppercase_count = 0
# Iterate over each character in the string
for char in my_string:
# Check if the character is uppercase
if char.isupper():
uppercase_count += 1
# Print the uppercase count
print("The number of uppercase letters in the string is:", uppercase_count)
Output:
The number of uppercase letters in the string is: 4
In the above example, the isupper()
method is called on each character in the my_string
string using a for
loop. If the character is uppercase, the uppercase_count
counter is incremented. After iterating over all characters in the string, the uppercase_count
variable will contain the total count of uppercase letters in the string.
+ There are no comments
Add yours