Python: loop over consecutive characters?


In Python (specifically Python 3.0 but I don't think it matters), how do I easily write a loop over a sequence of characters having consecutive character codes? I want to do something like this pseudocode:

for Ch from 'a' to 'z' inclusive: #

Example: how about a nice "pythonic" version of the following?

def Pangram(Str):
    ''' Returns True if Str contains the whole alphabet, else False '''
    for Ch from 'a' to 'z' inclusive: #
        M[Ch] = False
    for J in range(len(Str)):
        Ch = lower(Str[J])
        if 'a' <= Ch <= 'z':
            M[Ch] = True
    return reduce(and, M['a'] to M['z'] inclusive) #

The lines marked # are pseudocode. Of course reduce() is real Python!

Dear wizards (specially old, gray-bearded wizards), perhaps you can tell that my favorite language used to be Pascal.

9/18/2012 5:02:14 PM

You have a constant in the string module called ascii_lowercase, try that out:

>>> from string import ascii_lowercase

Then you can iterate over the characters in that string.

>>> for i in ascii_lowercase :
...     f(i)

For your pangram question, there is a very simple way to find out if a string contains all the letters of the alphabet. Using ascii_lowercase as before,

>>> def pangram(str) :
...     return set(ascii_lowercase).issubset(set(str))
2/5/2009 3:47:46 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow