Write a Python program to Count all lower case, upper case, digits, and special symbols from a given string

1. Introduction

In this blog post, we will write a Python program to count all lowercase letters, uppercase letters, digits, and special symbols in a given string. This is a practical example of how string manipulation and character classification can be achieved in Python.

2. Program Steps

1. Create a function that takes a string as an argument.

2. Initialize counters for lowercase, uppercase, digits, and special symbols.

3. Iterate over each character in the string and update the respective counter based on its type.

4. Return or print the counts of each type of character.

3. Code Program


def count_characters(input_string):
    # Step 2: Initialize counters
    lowercase_count = 0
    uppercase_count = 0
    digit_count = 0
    special_count = 0

    # Step 3: Iterate over each character in the string
    for char in input_string:
        if char.islower():
            lowercase_count += 1
        elif char.isupper():
            uppercase_count += 1
        elif char.isdigit():
            digit_count += 1
        else:
            special_count += 1

    # Step 4: Return the counts
    return lowercase_count, uppercase_count, digit_count, special_count

# Example usage
input_str = "Python3.8@OpenAI"
result = count_characters(input_str)
print(f"Lowercase: {result[0]}, Uppercase: {result[1]}, Digits: {result[2]}, Special symbols: {result[3]}")

Output:

For the input string 'Python3.8@OpenAI', the output will be:
Lowercase: 5, Uppercase: 4, Digits: 2, Special symbols: 2

Explanation:

1. The function count_characters takes a string as input and initializes four counters for lowercase letters, uppercase letters, digits, and special symbols.

2. It iterates over each character in input_string using a for loop. The character's type is determined using char.islower(), char.isupper(), char.isdigit(), and the else clause is for special symbols.

3. Each character is counted based on its type by incrementing the respective counter.

4. Finally, the function returns a tuple containing the counts of lowercase, uppercase, digits, and special symbols.

5. The function is called with the example string 'Python3.8@OpenAI', and it correctly counts and categorizes each character type.

This program showcases how to analyze and categorize different types of characters in a string in Python.


Comments