Number of occurrences of a character in a string

I just go into Python and I create a program that analyzes a group of words and returns how many times each letter appears in the text. ie 'A: 10, B: 3, C: 5 ... etc.'. While it works fine, except that I am looking for a way to condensate the code, so I do not write out each part of the program 26 times. Here is 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) 
+7
python
source share
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 this, which I'm sure others will point out, but first study this path until you understand it. This applies to very simple operations.

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

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

Again, there are shorter ways to do this, but this method adheres to very simple operations.

+13
source share

You can use a counter, but @TimPeters is probably right, and it's 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)) 
+12
source share

All Articles