Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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).</p> <p>You can use string.lowercase, as other posters have suggested:</p> <pre><code>import string allTheLetters = string.lowercase </code></pre> <p>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:</p> <pre><code>def getAllTheLetters(begin='a', end='z'): beginNum = ord(begin) endNum = ord(end) for number in xrange(beginNum, endNum+1): yield chr(number) </code></pre> <p>You can tell it does the right thing because this code prints <code>True</code>:</p> <pre><code>import string print ''.join(getAllTheLetters()) == string.lowercase </code></pre> <p>But, to solve the problem you're actually trying to solve, you want to use a dictionary and collect the letters as you go:</p> <pre><code>from collections import defaultdict def letterOccurrances(string): frequencies = defaultdict(lambda: 0) for character in string: frequencies[character.lower()] += 1 return frequencies </code></pre> <p>Use like so:</p> <pre><code>occs = letterOccurrances("Hello, world!") print occs['l'] print occs['h'] </code></pre> <p>This will print '3' and '1' respectively.</p> <p>Note that this works for unicode as well:</p> <pre><code># -*- coding: utf-8 -*- occs = letterOccurrances(u"héĺĺó, ẃóŕĺd!") print occs[u'l'] print occs[u'ĺ'] </code></pre> <p>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.</p> <p>To implement your original function (print the counts of each letter in alphabetical order) in terms of this:</p> <pre><code>def alphCount(text): for character, count in sorted(letterOccurrances(text).iteritems()): print "%s: %s" % (character, count) alphCount("hello, world!") </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload