for generating binary numbers in n
digit
i did this to get upto 16 binary numbers.
n = 6 # for 6 digits
for i in xrange(16):
b = bin(i)[2:]
l = len(b)
b = str(0) * (n - l) + b
print b
it results like this
000000
000001
000010
000011
000100
000101
000110
000111
001000
001001
001010
001011
001100
001101
001110
001111
but what i want is to get these values without adding a series of 0s
in prefix.
can anyone help me for this.
thanks
Remove the line that pad 0
s.
n = 6
for i in xrange(16):
b = bin(i)[2:]
l = len(b)
#b = str(0) * (n - l) + b # <--------
print b
If you mean padding number without string oeprator, use str.format
with b
type format:
n = 6
for i in xrange(16):
print '{:0{}b}'.format(i, n)
# OR print '{:06b}'.format(i)
# OR print '{:b}'.format(i) if you want no leading 0s.
If you're asking for a different method:
n = 6
for i in xrange(16):
b = bin(i)[2:].zfill(n)
print b
str.zfill(n)
pads the string with zeros on the left so that it is at least of length n
.
If you just don't want the leading zeros:
for i in xrange(16):
b = bin(i)[2:]
print b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With