pythoncount

Count character occurrences in a Python string


I want to get the each character count in a given sentence. I tried the below code and I got the count of every character but it displays the repeated characters count in the output. How to delete repeated character.

def countwords(x):
    x=x.lower()
    for i in x:
        print(i,'in',x.count(i)) 

x=str(input("Enter a paragraph "))
countwords(x)

My output is:

enter image description here

My output should not contain spaces count and repeated characters.. What to do....!!!


Solution

  • check this code :

    my_string = "count a character occurance"
    my_list = list(my_string)
    print (my_list)
    get_unique_char = set(my_list)
    print (get_unique_char)
    
    for key in get_unique_char:
        print (key, my_string.count(key))