Tuesday, 21 September 2021

Python: Count number of digits, lowercase, uppercase characters in a string

Using islower, isupper and isdigit methods, we can count number of digits, lowercase and uppercase characters in a string.

 

count_lower_upper_digits.py

def count_lower_upper_digits(input_str):
    result = {
        'upper': 0,
        'lower': 0,
        'digit': 0
    }

    for ch in input_str:
        if ch.isupper():
            result['upper'] += 1
        elif ch.islower():
            result['lower'] += 1
        elif ch.isdigit():
            result['digit'] += 1

    return result

input = '123Hello Wo12rlD'

print('Number of digits, lower and uppercase characters in "',input,'" are ', count_lower_upper_digits(input))

 

Output

Number of digits, lower and uppercase characters in " 123Hello Wo12rlD " are  {'upper': 3, 'lower': 7, 'digit': 5}

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment