Character Count in a String (Python)

vegaseat 0 Tallied Votes 875 Views Share

Create a dictionary with char:count pairs, change the dictionary to a list of (char, count) tuples, sort the list by character and display the result. That's all there is to counting and displaying the characters in a given string. Just a few lines of Python code.

# character count in a string
# tested with Python24      vegaseat     11oct2005

str1 = 'supercalifragilisticexpialidocious'

print "Original String = %s\n" % str1

# count the characters in the string and create a dictionary of char:count pairs
charCount = {}
for char in str1:
    charCount[char] = charCount.get(char, 0) + 1
    
# result charCount = {'a': 3, 'c': 3, 'e': 2, 'd': 1, 'g': 1, 'f': 1, ... }

# creates a sorted list of pair-tuples
sortedCharTuples = sorted(charCount.items())

# result sortedCharTuples = [('a', 3), ('c', 3), ('d', 1), ('e', 2), ('f', 1), ('g', 1), ...]

print "Character count in alphabetical order:"
for charTuple in sortedCharTuples:
    print "%s = %d" % (charTuple[0], charTuple[1])
    
""" result =
a = 3
c = 3
d = 1
e = 2
f = 1
g = 1
i = 7
...

"""