How do you count the frequency of each character in a string in python?


Text processing has emerged as an important field in machine learning and AI. Python supports this filed with many available tools and libraries. In this article we will see how we can find the number of occurrence of each letter of a given string.

With Counter

The Counter method counts the number of occurrences of an element in an iterable. So it is straight forward to use by passing the required string into it.

Example

 Live Demo

from collections import Counter

# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

for keys in strA:
res[keys] = res.get(keys, 0) + 1

# Result
print("Frequency of each character :\n ",res)

Output

Running the above code gives us the following result −

Output

Given String: timeofeffort
Frequency of each character :
{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}

With get()

We can treat the string as a dictionary and count the keys for each character using get() in a for loop.

Example

 Live Demo

# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

for keys in strA:
res[keys] = res.get(keys, 0) + 1

# Result
print("Frequency of each character :\n ",res)

Output

Running the above code gives us the following result −

Given String: timeofeffort
Frequency of each character :
{'t': 2, 'i': 1, 'm': 1, 'e': 2, 'o': 2, 'f': 3, 'r': 1}

With set

A set in python stores unique elements. So we can use it wisely by counting the number of times the same character is encountered again and again when looping through the string as an iterable.

Example

 Live Demo

# Given string
strA = "timeofeffort"
print("Given String: ",strA)
# Using counter
res = {}

res={n: strA.count(n) for n in set(strA)}

# Result
print("Frequency of each character :\n ",res)

Output

Running the above code gives us the following result −

Given String: timeofeffort
Frequency of each character :
{'f': 3, 'r': 1, 'm': 1, 'o': 2, 'i': 1, 't': 2, 'e': 2}

How do you count the frequency of each character in a string in python?

Updated on 05-May-2020 10:23:52

  • Related Questions & Answers
  • Find frequency of each word in a string in Python
  • Check if frequency of character in one string is a factor or multiple of frequency of same character in other string in Python
  • Print number of words, vowels and frequency of each character
  • Find frequency of each word in a string in C#
  • Find frequency of each word in a string in Java
  • Python – Sort String list by K character frequency
  • Write a C Program to count the frequency of each character
  • Encoding string based on character frequency in JavaScript
  • C program to find frequency of each digit in a string
  • Java program to check occurrence of each character in String
  • Java program to check occurence of each character in String
  • Java Program to Find the Frequency of Character in a String
  • Python program to find occurrence to each character in given string
  • How to Count Occurrences of Each Character in String in Android?
  • C++ Program to Find the Frequency of a Character in a String

In this python program, we will be  Calculating the Frequency of a character in a string or how many times a character is present in a string.

The string is a datatype in programing language and is formed when 2 or more characters join or concatenate together. Now it is not necessary for a string to have a distinct character, it can be meaningless or meaningful can have distinct characters or can be a combination of the same characters.

How do you count the frequency of each character in a string in python?

Method 1

This method is the most naive method –

  • Iterate on the input string
  • For each character in string count and prints its frequency
  • Use .count() method to do so.

Run

string = "Yolo Life"

for i in string:
    frequency = string.count(i)
    print(str(i) + ": " + str(frequency), end=", ")

Output

Y: 1, o: 2, l: 1, o: 2, : 1, L: 1, i: 1, f: 1, e: 1, 

Method 2

This method uses a dictionary in python.

  • Iterate on the input string
  • If a character appears for the first time, add key: char and value: 1
  • If char already exists in the dictionary increment the value counter by 1 against key char

Run

str = "YOLO LIFE"

# create dictionary to store key value pair
dict = {}

for i in str:
    # if i already appears as key in dict, increment the count
    if i in dict:
        dict[i] += 1

    # else i appears for the first time, add to dict
    else:
        dict[i] = 1

# printing result 
print(dict)

Output

{'Y': 1, 'O': 2, 'L': 2, ' ': 1, 'I': 1, 'F': 1, 'E': 1}

Method 3 (Using Counter)

This method uses a counter from collections

Run

from collections import Counter
string = "Yolo Life"

output = Counter(string)

print(output)

Output

Counter({'o': 2, 'Y': 1, 'l': 1, ' ': 1, 'L': 1, 'i': 1, 'f': 1, 'e': 1})

Method 4 Using Set() and Count()

This method is better than the previous method that used count as we are converting the string into a set of unique items.

So, Loop will not run for duplicate items and only for unique items in the set()

Run

string = "aabbbccccdddddeeeeee"

# using set() reduces string "YOLO LIFE" with 20 items
# to a set of 5 items : {'a', 'b', 'c', 'd', 'e'}
# now print count each item in set appearing in string
# storing result as dictionary
# for loop runs only 5 times
res = {i: string.count(i) for i in set(string)}

print(res)

Output

{'a': 2, 'c': 4, 'b': 3, 'e': 6, 'd': 5}

Method 5 Using dict.get()

The get() method returns the value of the item with the specified key.

Run

string = "YOLO LIFE"

res = {}

for key in string:
    # if item doesn't exist res.get(key, 0) returns 0 as result
    # we use res.get(key, 0) + 1 so as to initialize value as 1 on first occurrence
    # if item exits then res.get(key, 0) + 1 just increments the previously held value
    res[key] = res.get(key, 0) + 1

# printing result
print (res)

Output

{'Y': 1, 'O': 2, 'L': 2, ' ': 1, 'I': 1, 'F': 1, 'E': 1}

Note Time Complexity: O(n), where n is the number of characters in the string.

How do you count the frequency of each character in a string in python?

How do you find the frequency of each character in a string?

Python.
string = "picture perfect";.
freq = [None] * len(string);.
for i in range(0, len(string)):.
freq[i] = 1;.
for j in range(i+1, len(string)):.
if(string[i] == string[j]):.
freq[i] = freq[i] + 1;.
#Set string[j] to 0 to avoid printing visited character..

How do you count the frequency of words in a string in Python?

Use set() method to remove a duplicate and to give a set of unique words. Iterate over the set and use count function (i.e. string. count(newstring[iteration])) to find the frequency of word at each iteration.

How do you find the frequency of each element in a list in Python?

We are going to use a module method to find the frequency of elements..
Import the collections module..
Initialize the list with elements..
Get the frequency of elements using Counter from collections module..
Convert the result to dictionary using dict and print the frequency..