In this article we will discuss different ways to fetch the frequency or occurrence count of each character in the string and their index positions in the string using collections.Counter() and regex.

Get Frequency of each character in string using collections.Counter()

Counter is a dict subclass and collections.Counter() accepts an iterable entity as argument and keeps the elements in it as keys and their frequency as values. So, if we pass a string in collections.Counter() then it will return a Counter class object which internally has all characters in string as keys and their frequency in string as values. So, let’s use that to find the frequency of all characters in a string i.e.

Output:

This way we got the occurrence count of all the characters in the string including ‘ ‘ and ‘.’. What if want the frequency of only characters & numbers, also their index positions in a list. Let’s see how to do that,

Python Regex : Get frequency of each character in string

We will create a regex pattern to match all the alphanumeric characters in the string i.e.

Now iterate over all the matches of above pattern in the string using pattern.finditer() and create dictionaries of frequency count of each character and their index positions in the string i.e.

Output

Find Duplicate characters in a String using collections.Counter()

Suppose we have a string i.e.

Now to find all the duplicate characters in this string, use collections.Counter() to find the frequency of each character in string and characters which has frequency more than 2 are duplicate ones i.e.

Output:

Complete example is as follows,

Output

 

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,