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.
See string constants for the other possibilities, including uppercase, numbers, locale-dependent characters, all of which you can join together like
string.ascii_uppercase + string.ascii_lowercase
if you want all of the characters in multiple sets.Use list comprehension:
Another option (operates like range - add 1 to stop if you want stop to be inclusive)
There are other good answers here (personally I'd probably use string.lowercase), but for the sake of completeness, you could use map() and chr() on the lower case ascii values:
I like an approach which looks like this:
It certainly can be implemented with a lot of more comfort, but it is quick and easy and very readable.
Python 3
Generator version:
Or, if you like list comprehensions:
The first yields:
while the second yields:
It is really convenient:
outputs
Why the
list()
? Withoutbase64chars
might become a generator (depending on the implementation you chose) and thus can only be used in the very first loop.Python 2
Similar can be archived with Python 2. But it is far more complex if you want to support Unicode, too. To encourage you to stop using Python 2 in favor of Python 3 I do not bother to provide a Python 2 solution here ;)
Proper handling of Unicode in Python 2 is extremely complex, and it is nearly impossible to add Unicode support to Python 2 projects if this support was not build in from the beginning.
Hints how to backport this to Python 2:
xrange
instead ofrange
unicodes
?) for handling of Unicode:unichr
instead ofchr
to returnunicode
instead ofstr
unicode
strings asargs
to makeord
and array subscript work properlyInspired from the top post above, I came up with this :