Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the pythonic way of generating a range of chars?

Tags:

python

In other languages, I would use a construct like this:

a..z

I couldn't come up with a better solution than this:

[chr(x) for x in range(ord("a"), ord("z") + 1)]

Is there a shorter, more readable way of building such a list ?

like image 666
Jeremy Avatar asked Jan 28 '12 21:01

Jeremy


2 Answers

Not necessarily great if you want to do something other than a to z, but you can do this:

from string import ascii_lowercase
for c in ascii_lowercase:
    print c
like image 110
Nathan Binkert Avatar answered Sep 22 '22 07:09

Nathan Binkert


My way is similar to yours but you can use map and create an arbitrary function like this

>>> def generate_list(char1,char2):
...      myl = map(chr, range(ord(char1),ord(char2)+1))
...      print myl
...
>>> generate_list("a","d")
['a', 'b', 'c', 'd']
like image 23
RanRag Avatar answered Sep 19 '22 07:09

RanRag