Range over character in python

Is there a way to navigate through characters? something like that.

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

Hope you guys can help.

+65
python character range
Aug 09 '11 at 18:37
source share
14 answers

This is a great use for your own 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) 
+85
Aug 09 '11 at 18:52
source share
 import string for char in string.ascii_lowercase: print char 

See string constants for other features, including uppercase, numbers, language dependent characters, all of which you can combine, for example string.ascii_uppercase + string.ascii_lowercase if you want all characters in multiple sets.

+71
Aug 09 '11 at 18:49
source share

You need to convert characters to numbers and vice versa.

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

For 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 using inclusive=False (default) to simulate the usual Python bhehaviour to exclude the final element or using inclusive=True (default) to enable it. Thus, by default, inclusive=False , 'a', 'z' will simply cover the range from a to y , excluding z .

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

Currently (possibly) only works in Py2.

+24
Aug 09 '11 at 18:40
source share

There are other good answers here (personally, I probably used string.lowercase), but for completeness you can use map () and chr () for lowercase ascii values:

 for c in map(chr, xrange(97, 123)): print c 
+10
Aug 09 '11 at 19:27
source share
 for character in map( chr, xrange( ord('a'), ord('c')+1 ) ): print character 

prints:

 a b c 
+5
Oct 02 '13 at 8:54 on
source share
 # generating 'a to z' small_chars. small_chars = [chr(item) for item in range(ord('a'), ord('z')+1)] # generating 'A to Z' upper chars. upper_chars = [chr(item).upper() for item in range(ord('a'), ord('z')+1)] 
+5
Nov 17 '14 at 19:23
source share

If you have a short fixed list of characters, just use Python to process strings as lists.

 for x in 'abcd': print x 

or

 [x for x in 'abcd'] 
+5
Dec 12 '14 at 18:35
source share

I like the approach that looks like this:

 base64chars = list(chars('AZ', 'az', '09', '++', '//')) 

It can certainly be implemented with great comfort, but it is quick and easy and easy to read.

Python 3

Generator Version:

 def chars(*args): for a in args: for i in range(ord(a[0]), ord(a[1])+1): yield chr(i) 

Or if you like the listings:

 def chars(*args): return [chr(i) for a in args for i in range(ord(a[0]), ord(a[1])+1)] 

The first gives:

 print(chars('ĀĈ')) <generator object chars at 0x7efcb4e72308> print(list(chars('ĀĈ'))) ['Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ'] 

and the second gives:

 print(chars('ĀĈ')) ['Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ'] 

This is really convenient:

 base64chars = list(chars('AZ', 'az', '09', '++', '//')) for a in base64chars: print(repr(a),end='') print('') for a in base64chars: print(repr(a),end=' ') 

exits

 'A''B''C''D''E''F''G''H''I''J''K''L''M''N''O''P''Q''R''S''T''U''V''W''X''Y''Z''a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''s''t''u''v''w''x''y''z''0''1''2''3''4''5''6''7''8''9''+''/' 'A' 'B' 'C' 'D' 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' 'P' 'Q' 'R' 'S' 'T' 'U' 'V' 'W' 'X' 'Y' 'Z' 'a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y' 'z' '0' '1' '2' '3' '4' '5' '6' '7' '8' '9' '+' '/' 

Why list() ? Without base64chars can become a generator (depending on the implementation you choose) and, therefore, can only be used in the very first cycle.

Python 2

Similar ones can be archived with Python 2. But this is much more complicated if you want to also support Unicode. To encourage you to stop using Python 2 in favor of Python 3, I don't want to offer a Python 2 solution here;)

Try avoiding Python 2 today for new projects. Also, try porting your old projects to Python 3 first before expanding them - in the end, it will be worth the effort!

Proper Unicode handling in Python 2 is extremely complex, and it is almost impossible to add Unicode support for Python 2 projects if that support was not created from the very beginning.

Specifies how to back up this file in Python 2:

  • Use xrange instead of range
  • Create a second function ( unicodes ?) To handle Unicode:
    • Use unichr instead of chr to return unicode instead of str
    • Never forget to feed unicode strings as args to make ord and array index work correctly
+4
Jun 24 '17 at 9:03 on
source share

Inspired from above from above, I came up with this:

 map(chr,range(ord('a'),ord('z')+1)) 
+3
Apr 03 '16 at 5:03
source share

Use "to count in range" and chr & ord:

 print [chr(ord('a')+i) for i in range(ord('z')-ord('a'))] 
0
Dec 07 '15 at 3:43 on
source share

Use list:

 for c in [chr(x) for x in range(ord('a'), ord('z'))]: print c 
0
Feb 04 '16 at 22:51
source share

Using the @ ned-batchelder answer here, I'm slightly correcting it for python3

 def char_range(c1, c2): """Generates the characters from `c1` to `c2`, inclusive.""" """Using range instead of xrange as xrange is deprecated in Python3""" for c in range(ord(c1), ord(c2)+1): yield chr(c) 

Then the same as in Ned:

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

Thanks Ned!

0
Apr 15 '16 at 8:23
source share

Another option (works like a range - adds 1 to stop if you want the stop to be turned on)

 >>> import string >>> def crange(arg, *args): ... """character range, crange(stop) or crange(start, stop[, step])""" ... if len(args): ... start = string.ascii_letters.index(arg) ... stop = string.ascii_letters.index(args[0]) ... else: ... start = string.ascii_letters.index('a') ... stop = string.ascii_letters.index(arg) ... step = 1 if len(args) < 2 else args[1] ... for index in range(start, stop, step): ... yield string.ascii_letters[index] ... >>> [_ for _ in crange('d')] ['a', 'b', 'c'] >>> >>> [_ for _ in crange('d', 'g')] ['d', 'e', 'f'] >>> >>> [_ for _ in crange('d', 'v', 3)] ['d', 'g', 'j', 'm', 'p', 's'] >>> >>> [_ for _ in crange('A', 'G')] ['A', 'B', 'C', 'D', 'E', 'F'] 
0
Apr 19 '17 at 21:43 on
source share

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 helps someone

0
Feb 05 '19 at 15:42
source share



All Articles