Alex Rivera | Logout

Python: loop over consecutive characters?

Asked 2009-02-05T03:41:31.537
16

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: #
    f(Ch)

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.

Edit
Report

1 Answer

21

Iterating a constant with all the characters you need is very Pythonic. However if you don't want to import anything and are only working in Unicode, use the built-ins ord() and its inverse chr().

for code in range(ord('a'), ord('z') + 1):
     print(chr(code))
answered 2009-02-05T04:04:39.540

Your Answer