Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character count in string

Tags:

python

def charcount(stri):
    for i in stri:
        count = 0
        for j in stri:
            if stri[i] == stri[j]:
                count += 1

I am new to python and currently learning string operations, can anyone tell me what is wrong in this program? The function tries to print a count of each character in given string.

For eg: string ="There is shadow behind you" I want to count how many times each character have come in string

like image 377
Chandan Avatar asked Jul 13 '26 09:07

Chandan


1 Answers

Counting characters in a string can be done with the Counter() class like:

Code:

from collections import Counter

def charcount(stri):
    return Counter(stri)

print(charcount('The function try to print count of each character '
                'in given string . Please help'))

Results:

Counter({' ': 14, 'e': 7, 'n': 7, 't': 7, 'c': 5, 'i': 5, 
         'r': 5, 'h': 4, 'o': 4, 'a': 4, 'f': 2, 'u': 2, 
         'p': 2, 'g': 2, 's': 2, 'l': 2, 'T': 1, 'y': 1, 
         'v': 1, '.': 1, 'P': 1})
like image 121
Stephen Rauch Avatar answered Jul 17 '26 11:07

Stephen Rauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!