Search code examples
pythonbinaryformathex

Python format() to print the decimal, oct, hex, and binary values


I am trying to use .format() in python I wish to print

1 to N with space padding so that all fields take the same width as the binary value.

Below is what i have tried till now

n=int(input()) 
width = len("{0:b}".format(n)) 
for num in range(1,n+1):
    print ('  '.join(map(str,(num,oct(num).replace('0o',''),hex(num).replace('0x',''),bin(num).replace('0b','')))))

I don't know how to use the .format() function properly here. Kindly help


Solution

  • Below code finds all hexadecimal,binary,octal and decimal values

    n = int(input())
    w = len("{0:b}".format(n))
    for i in range(1,n+1):
      print ("{0:{width}d} {0:{width}o} {0:{width}x} {0:{width}b}".format(i, width=w))