Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the number of occurrences of each character

Tags:

python

string

Given the string:

a='dqdwqfwqfggqwq'

How do I get the number of occurrences of each character?

like image 669
zjm1126 Avatar asked Mar 04 '11 10:03

zjm1126


People also ask

How do you count occurrences of a character?

Initialize a counter variable to store the count of total occurrences of a character in a string. Traverse the string character by character. If the character of the string matches with the given character, increment the value of the count variable. Finally, return the counter variable.

How do you count occurrences of each character in a string?

In order to find occurence of each character in a string we can use Map utility of Java.In Map a key could not be duplicate so make each character of string as key of Map and provide initial value corresponding to each key as 1 if this character does not inserted in map before.

How do you count the number of occurrences of a character in Python?

count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.


2 Answers

In 2.7 and 3.1 there's a tool called Counter:

>>> import collections
>>> results = collections.Counter("dqdwqfwqfggqwq")
>>> results
Counter({'q': 5, 'w': 3, 'g': 2, 'd': 2, 'f': 2})

Docs. As pointed out in the comments it is not compatible with 2.6 or lower, but it's backported.

like image 149
Bjorn Avatar answered Oct 03 '22 01:10

Bjorn


Not highly efficient, but it is one-line...

In [24]: a='dqdwqfwqfggqwq'

In [25]: dict((letter,a.count(letter)) for letter in set(a))
Out[25]: {'d': 2, 'f': 2, 'g': 2, 'q': 5, 'w': 3}
like image 38
unutbu Avatar answered Oct 03 '22 00:10

unutbu