How do I iterate through a string in Python?
Question: As an example, lets say I wanted to list the frequency of each letter of the
alphabet in a string. What would be the easiest way to do it?

This is an example of what I'm thinking of... the question is how to make
allTheLetters equal to said letters without something like allTheLetters =
"abcdefg...xyz". In many other languages I could just do letter++ and
increment my way through the alphabet, but thus far I haven't come across a
way to do that in python.

    
    
    def alphCount(text):
      lowerText = text.lower()
      for letter in allTheLetters:  
        print letter + ":", lowertext.count(letter)
    


Answer: The question you've asked (how to iterate through the alphabet) is not the
same question as the problem you're trying to solve (how to count the
frequency of letters in a string).

You can use string.lowercase, as other posters have suggested:

    
    
    import string
    allTheLetters = string.lowercase
    

To do things the way you're "used to", treating letters as numbers, you can
use the "ord" and "chr" functions. There's absolutely no reason to ever do
exactly this, but maybe it comes closer to what you're actually trying to
figure out:

    
    
    def getAllTheLetters(begin='a', end='z'):
        beginNum = ord(begin)
        endNum = ord(end)
        for number in xrange(beginNum, endNum+1):
            yield chr(number)
    

You can tell it does the right thing because this code prints `True`:

    
    
    import string
    print ''.join(getAllTheLetters()) == string.lowercase
    

But, to solve the problem you're actually trying to solve, you want to use a
dictionary and collect the letters as you go:

    
    
    from collections import defaultdict    
    def letterOccurrances(string):
        frequencies = defaultdict(lambda: 0)
        for character in string:
            frequencies[character.lower()] += 1
        return frequencies
    

Use like so:

    
    
    occs = letterOccurrances("Hello, world!")
    print occs['l']
    print occs['h']
    

This will print '3' and '1' respectively.

Note that this works for unicode as well:

    
    
    # -*- coding: utf-8 -*-
    occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!")
    print occs[u'l']
    print occs[u'ĺ']
    

If you were to try the other approach on unicode (incrementing through every
character) you'd be waiting a long time; there are millions of unicode
characters.

To implement your original function (print the counts of each letter in
alphabetical order) in terms of this:

    
    
    def alphCount(text):
        for character, count in sorted(letterOccurrances(text).iteritems()):
            print "%s: %s" % (character, count)
    
    alphCount("hello, world!")
    

