Python Count the Uppercase Letters in a String
This program computes and prints the number of uppercase letters in a given string.
Example
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
)
(
f
"The number of uppercase letters in the string is: {uppercase_count}"
)
Code analysis:
- defined a function
count_uppercase_letters, which takes a stringsas its argument. - Initialize a counter
countis 0. - Use
forLoop over every character in the stringchar。 - Use
char.isupper()The method checks whether the current character is an uppercase letter. If so, the countercountis incremented by 1. - After the loop ends, return the counter's value.
- Define an example string
sample_stringand call thecount_uppercase_lettersfunction to count the uppercase letters in it. - Use
printfunction to output the result.
Output result:
The number of uppercase letters in the string is: 4
Python3 Examples