range over character in python range over character in python python python

range over character in python


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)


import stringfor char in string.ascii_lowercase:    print char

See string constants for the other possibilities, including uppercase, numbers, locale-dependent characters, all of which you can join together like string.ascii_uppercase + string.ascii_lowercase if you want all of the characters in multiple sets.


You have to convert the characters to numbers and back again.

for c in xrange(ord('a'), ord('z')+1):    print chr(c) # resp. print unicode(c)

For the sake of beauty and readability, you can wrap this in a generator:

def character_range(a, b, inclusive=False):    back = chr    if isinstance(a,unicode) or isinstance(b,unicode):        back = unicode    for c in xrange(ord(a), ord(b) + int(bool(inclusive)))        yield back(c)for c in character_range('a', 'z', inclusive=True):    print(chr(c))

This generator can be called with inclusive=False (default) to imitate Python's usual bhehaviour to exclude the end element, or with inclusive=True (default) to include it. So with the default inclusive=False, 'a', 'z' would just span the range from a to y, excluding z.

If any of a, b are unicode, it returns the result in unicode, otherwise it uses chr.

It currently (probably) only works in Py2.