range over character in python

huan picture huan · Aug 9, 2011 · Viewed 81k times · Source

Is there an way to range over characters? something like this.

for c in xrange( 'a', 'z' ):
    print c

I hope you guys can help.

Answer

Ned Batchelder picture Ned Batchelder · Aug 9, 2011

This is a great use for a custom generator:

Python 2:

def char_range(c1, c2):
    """Generates the characters from `c1` to `c2`, inclusive."""
    for c in xrange(ord(c1), ord(c2)+1):
        yield chr(c)

then:

for c in char_range('a', 'z'):
    print c

Python 3:

def char_range(c1, c2):
    """Generates the characters from `c1` to `c2`, inclusive."""
    for c in range(ord(c1), ord(c2)+1):
        yield chr(c)

then:

for c in char_range('a', 'z'):
    print(c)