Tuesday, 21 September 2021

Python: Count number of digits in a string

By iterating over the string character by character, and ‘isdigit’ method  we can count number of digits in a string.

 

count_digits.py

def count_digits(input_str):
    count = 0

    for ch in input_str:
        if ch.isdigit():
            count += 1

    return count

input = '123Hello Wo12rlD'

print('Number of digits in "',input,'" is ', count_digits(input))

Output

Number of digits in " 123Hello Wo12rlD " is  5


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment