Home ยป Count Character Frequency of a String using python

Count Character Frequency of a String using python

Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course
1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests

In this example we use python to count the character frequency of a string

Table of Contents

Example 1

In this Python example, the for loop iterates through the whole string that the user inputs.

We then assign all the count of characters to the dictionary keys.

myString = input("Please enter the Your Own String = ")
dictchars = {}

for num in myString:
    keys = dictchars.keys()
    if num in keys:
        dictchars[num] += 1
    else:
        dictchars[num] = 1

print(dictchars)

You will see the following

>>> %Run countcharfreq.py
Please enter the Your Own String = This is a test string to count characters
{'T': 1, 'h': 2, 'i': 3, 's': 5, ' ': 7, 'a': 3, 't': 6, 'e': 2, 'r': 3, 'n': 2, 'g': 1, 'o': 2, 'c': 3, 'u': 1}

Example 2

We will use a collection in this example

from collections import Counter

myString = input("Please enter the Your Own String = ")

chars = Counter(myString)

print("Total Character Frequency in this String = ")
print(chars)

You will see the following

>>> %Run countercharfreq1.py
Please enter the Your Own String = This is a test string to count characters
Total Character Frequency in this String = 
Counter({' ': 7, 't': 6, 's': 5, 'i': 3, 'a': 3, 'r': 3, 'c': 3, 'h': 2, 'e': 2, 'n': 2, 'o': 2, 'T': 1, 'g': 1, 'u': 1})

You will see we have used the string but this example puts the character by frequency from highest to lowest

Link

This is in our github repository

https://github.com/programmershelp/maxpython/tree/main/code%20example/String%20examples

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More