Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Count the Uppercase Letters in a String

Python Count the Uppercase Letters in a String

Document Object Reference Manual Python3 Examples

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

)

print

(

f

"The number of uppercase letters in the string is: {uppercase_count}"

)

Code analysis:

  1. defined a function count_uppercase_letters, which takes a string s as its argument.
  2. Initialize a counter count is 0.
  3. Use for Loop over every character in the string char。
  4. Use char.isupper() The method checks whether the current character is an uppercase letter. If so, the counter count is incremented by 1.
  5. After the loop ends, return the counter's value.
  6. Define an example string sample_stringand call the count_uppercase_letters function to count the uppercase letters in it.
  7. Use print function to output the result.

Output result:

The number of uppercase letters in the string is: 4

Document Object Reference Manual Python3 Examples