range over character in python

Viewed 106278

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.

16 Answers

For Uppercase Letters:

for i in range(ord('A'), ord('Z')+1):
    print(chr(i))

For Lowercase letters:

for i in range(ord('a'), ord('z')+1):
    print(chr(i))

i had the same need and i used this :

chars = string.ascii_lowercase
range = list(chars)[chars.find('a'):chars.find('k')+1]

Hope this will Help Someone

Depending on how complex the range of characters is, a regular expression may be convenient:

import re
import string

re.findall("[a-f]", string.printable)
# --> ['a', 'b', 'c', 'd', 'e', 'f']

re.findall("[n-qN-Q]", string.printable)
# --> ['n', 'o', 'p', 'q', 'N', 'O', 'P', 'Q']

This works around the pesky issue of accidentally including the punctuation characters in between numbers, uppercase and lowercase letters in the ASCII table.

Related