Python Count the Number of Uppercase Letters in a String
This program will calculate and output the number of uppercase letters in a given string.
Examples
def count_uppercase_letters(s):
count = 0
for char in s:
if char.isupper():
count += 1
return count
# Example string
sample_string = "Hello World! This is a Test."
uppercase_count = count_uppercase_letters(sample_string)
print(f"The number of uppercase letters in the string is: {uppercase_count}")
count = 0
for char in s:
if char.isupper():
count += 1
return count
# Example string
sample_string = "Hello World! This is a Test."
uppercase_count = count_uppercase_letters(sample_string)
print(f"The number of uppercase letters in the string is: {uppercase_count}")
Code explanation:
- Defines a function
count_uppercase_letters, it accepts a stringsas a parameter. - Initialize a counter
countto 0. - Use
fora loop to iterate through each character in the stringchar。 - Use
char.isupper()the method to check whether the current character is an uppercase letter. If so, the countercountincreases by 1. - After the loop ends, return the value of the counter.
- Define an example string
sample_string, and callcount_uppercase_lettersthe function to calculate the number of uppercase letters in it. - Use
printthe function to output the result.
Output result:
The number of uppercase letters in the string is: 4Other extensions
Python3 Examples