Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of occurrences of a character in a string

Tags:

python

I'm just getting into Python and I'm building a program that analyzes a group of words and returns how many times each letter appears in the text. i.e 'A:10, B:3, C:5...etc'. So far it's working perfectly except that i am looking for a way to condense the code so i'm not writing out each part of the program 26 times. Here's what I mean..

print("Enter text to be analyzed: ")
message = input()

A = 0
b = 0
c = 0
...etc

for letter in message:

    if letter == "a":
        a += 1
    if letter == "b":
        b += 1
    if letter == "c":
        c += 1
    ...etc

print("A:", a, "B:", b, "C:", c...etc)
like image 298
Kevin Arthur Avatar asked Sep 14 '13 03:09

Kevin Arthur


Video Answer


2 Answers

There are many ways to do this. Most use a dictionary (dict). For example,

count = {}
for letter in message:
    if letter in count:  # saw this letter before
        count[letter] += 1
    else:   # first time we've seen this - make its first dict entry
        count[letter] = 1

There are shorter ways to write it, which I'm sure others will point out, but study this way first until you understand it. This sticks to very simple operations.

At the end, you can display it via (for example):

for letter in sorted(count):
    print(letter, count[letter])

Again, there are shorter ways to do this, but this way sticks to very basic operations.

like image 119
Tim Peters Avatar answered Sep 30 '22 17:09

Tim Peters


You can use Counter but @TimPeters is probably right and it is better to stick with the basics.

from collections import Counter

c = Counter([letter for letter in message if letter.isalpha()])
for k, v in sorted(c.items()):
    print('{0}: {1}'.format(k, v))
like image 44
zero323 Avatar answered Sep 30 '22 16:09

zero323