top of page

Data Scientist Program


Free Online Data Science Training for Complete Beginners.

No prior coding knowledge required!

Count character occurrences in a given sentence using python

In this post we learn how count characters, special characters #*&@.... and spaces occurrences in a given word, phrase or sentence.

Get word, phrase or sentence from user.

sentence = input ("Enter sentence :")

Function Count character occurrences in a given word, phrase or sentence.

def count_characters(sentence):
    length = len(sentence)
    count = {'count':1}
    for i in range(length):
        if sentence[i] in count.keys():
            count[sentence[i] ] += 1
            count[sentence[i] ] = 1
    del count["count"]
    return count

- length is a number of characters in sentence including spcial character @ $ #... and spaces.

- creat dictionary keys are characters and values are count of characters.

- count in beging has key 1 if I put count empty it is occure an error in if statement .

- for loop all string sentence from first character sentence[0] to last character sentence[lenght-1] as string in python is an array and order start from zero not one.

- if element sentence[i] in keys if element sentence[i] in not in keys creat new keys neme's sentence[i] and put value by one increase this value.

- delete from dictionary key count.

Call function save it's return in variable result

result = count_characters(sentence)

Display dictionary using loop

for key in result :print(key , " : " , result[key]) 

you can git code and see run of the code click here


Recent Posts

See All


bottom of page