I have a small bit of code in Python 3 -
'{:08b}' .format(i)
that gives an error in Python 2.x. Does anyone know the equivalent?
Join Stack Overflow to learn, share knowledge, and build your career.
I have a small bit of code in Python 3 -
'{:08b}' .format(i)
that gives an error in Python 2.x. Does anyone know the equivalent?
Your original code actually works in Python 2.7. For Python 2.6, you need to introduce a reference to your format
argument - either an index (0
):
'{0:08b}'.format(i)
or a name:
'{x:08b}'.format(x=i) # or:
'{i:08b}'.format(i=i) # or even:
'{_:08b}'.format(_=i) # (since you don't care about the name)
Strangely enough, this particular quirk doesn't seem to be mentioned in the documentation about string formatting :(
'{:0>8s}' .format(bin(i)[2:])
. Clearly not worth posting as an answer ... (+1)
– mgilson
Dec 27 '13 at 18:50
'{0:08b}'.format(i)
? I think that should work on both python2.x and python3.x without a problem and it's still using positional arguments like the original...
– mgilson
Dec 27 '13 at 18:58
'{:08b}'.format(42)
in Python 3.3.1 and it works just fine.
– Xion
Dec 28 '13 at 10:51
Try this:
def fun(i):
print ('{0:08b}'.format(i))
fun(i) # Put any decimal number instead of i in fun(i) like fun(5). The result will be the binary code for number five which is 00000101