How to count the frequency of the digits (0 to 9) in a string with Python

1 Answer

0 votes
def countDigits(s) :
    size = len(s)
    
    if (size == 0) :
        print("String is empry", end ="")
        return
    
    digit_frequency = [0] * 10

    for i in range(size):
        if (s[i].isdigit()) :
            digit_frequency[ord(s[i]) - ord('0')] += 1 
    
    for i in range(10):
        print(i, ":", digit_frequency[i], "times")
    

s = "python23c++4523java23988rust82215"
countDigits(s)




'''
run:

0 : 0 times
1 : 1 times
2 : 5 times
3 : 3 times
4 : 1 times
5 : 2 times
6 : 0 times
7 : 0 times
8 : 3 times
9 : 1 times

'''

 



answered Jun 1, 2023 by avibootz
...