Q: Feature Wish: "%" Extension

Chris Liechti cliechti at gmx.net
Fri Nov 2 22:44:44 EST 2001


anonymous <no at spam.net> wrote in news:3BE34077.8EA553CB at spam.net:
[...]
> For number->string conversion (see it coming yet?), the handy overloaded
> "%" operator handles radices 8, 10, and 16 -- with padding,
> zero-filling, prefixing (e.g. "0x"). But every time I need to convert a
> number to _binary_, I have to call a function of my own to produce the
> string, and then intermingle that string with other numbers in the final
> "%" format I originally intended. It's awkward and slow.
> 
[...]

q = {'0':'0000', '1':'0001', '2':'0010', '3':'0011', '4':'0100', 
'5':'0101', '6':'0110', '7':'0111', '8':'1000', '9':'1001', 'a':'1010', 
'b':'1011', 'c':'1100', 'd':'1101', 'e':'1110', 'f':'1111'}

def bin(x): return ''.join(map(q.get,'%x' % x))

print "some text with a number 0b%s in it" % bin(123)

the above "bin" is 3x faster than this "foo":

def foo(x):
    r = []
    for b in range(len(hex(x))-2):
        r.append(x&(1<<b) and '1' or '0')
    r.reverse()
    return ''.join(r)

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list