Python Count the Number of Uppercase Letters in a String

Document 对象参考手册Python3 Examples

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}")

Code explanation:

  1. Defines a functioncount_uppercase_letters, it accepts a stringsas a parameter.
  2. Initialize a countercountto 0.
  3. Usefora loop to iterate through each character in the stringchar。
  4. Usechar.isupper()the method to check whether the current character is an uppercase letter. If so, the countercountincreases by 1.
  5. After the loop ends, return the value of the counter.
  6. Define an example stringsample_string, and callcount_uppercase_lettersthe function to calculate the number of uppercase letters in it.
  7. Useprintthe function to output the result.

Output result:

The number of uppercase letters in the string is: 4

Document 对象参考手册Python3 Examples

Other extensions