Range of characters?
Mari Mcdade
wurmy at earthlink.net
Wed Dec 26 12:27:54 EST 2001
David Brady wrote:
>
> Hello,
>
> I want to iterate over a range of characters, and
> though I have a solution, it "feels wrong"... I think
> (I hope, anyway) that I'm getting along well enough
> with Python that I can tell when I've strayed from the
> Pythonic Way. What's the best way to do this?
>
> Suppose, for example, that we want to generate every
> possible name for Python and it's clones, Aython,
> Bython, Cython, etc. Here is the code I would write
> to do it:
>
> for c in range(ord('A'), ord('Z')+1):
> print "%sython" % chr(c)
>
> It seems to me that flipping back and forth between
> ord and chr, and especially the ord('Z')+1 have a
> hackish smell to them. Is there a better way?
Your way isn't wrong, but Python can loop over
sequences of characters too, so why not use that:
>>> import string
>>> for c in string.uppercase:
print "%sython" % (c)
Aython
Bython
Cython
...
etc...
You don't need the string module, really, but using the literal
string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" seemed a bit ugly. ;-)
HTH,
--Hans
More information about the Python-list
mailing list