print a ... z, A ... Z, "\n"' in Python

MonkeeSage MonkeeSage at gmail.com
Sat Mar 3 11:44:53 CET 2007


js  wrote:
> A way I came up with is the following, but I'm sure this is ugly.

You could abuse __getitem__ (terribly, heh!) and use slice syntax...

class crange():
    def __init__(self):
        self.valid = range(47,58) + range(65,91) + range(97,123)
    def __getitem__(self, s):
        if isinstance(s, slice):
            start, stop = s.start, s.stop
            if not start: start = '0'
            if isinstance(stop, int) and stop > 122: stop = 'z'
            elif not stop: stop  = 'z'
            clist = []
            chars = range(ord(start), ord(stop)+1)
            for i in range(len(chars)):
                if chars[i] in self.valid:
                    clist.append(chr(chars[i]))
            return ''.join(clist)
        else:
            return s

cr = crange()
print cr['A':'z']
print cr['0':'8']
print cr[:]

Regards,
Jordan




More information about the Python-list mailing list