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.
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.
You have to convert the characters to numbers and back again.
For the sake of beauty and readability, you can wrap this in a generator:
This generator can be called with
inclusive=False
(default) to imitate Python's usual bhehaviour to exclude the end element, or withinclusive=True
(default) to include it. So with the defaultinclusive=False
,'a', 'z'
would just span the range froma
toy
, excludingz
.If any of
a
,b
are unicode, it returns the result in unicode, otherwise it useschr
.It currently (probably) only works in Py2.
prints:
Using @ned-batchelder's answer here, I'm amending it a bit for
python3
Then same thing as in Ned's answer:
Thanks Ned!
This is a great use for a custom generator:
Python 2:
then:
Python 3:
then:
If you have a short fixed list of characters, just use Python's treatment of strings as lists.
or