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

20,230

Solution 1

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))

Solution 2

# the simplest one.

def print_formatted(number):
    width=len(bin(number)[2:])
    for i in range(1,number+1):
        deci=str(i)
        octa=oct(i)[2:]
        hexa=(hex(i)[2:]).upper()
        bina=bin(i)[2:]
        print(deci.rjust(width),octa.rjust(width),hexa.rjust(width),bina.rjust(width))

Solution 3

Hackerrank String Formatting

def print_formatted(numbers):
   w = len("{0:b}".format(numbers))
   for i in range(1,n+1):
      o=oct(i)
      h=hex(i)
      b=bin(i)
      o=o.replace("0o","")
      h=h.replace("0x","")
      b=b.replace("0b","")
      print(str(i).rjust(w),o.rjust(w),h.upper().rjust(w),b.rjust(w))


if __name__ == '__main__':
   n = int(input())
   print_formatted(n)

Solution 4

Please have a look at https://docs.python.org/2/library/stdtypes.html#string-formatting where the conversion flags and conversion types are described.

As an example, the part to format your number in octal with the length width looks like this:

'{0:{w}o}'.format(n, w=width)

This will first create a formatted string that looks like this {0:4o} (with width = 4) and afterwards create the final string.

Solution 5

Below code print the decimal,oct,hex and binary values using format function in specifying width only

width = len('{:b}'.format(number))
for i in range(1,number+1):
    print(str.rjust(str(i),width),str.rjust(str(oct(i)[2:]),width),str.rjust(str(hex(i).upper()[2:]),width),str.rjust(str(bin(i)[2:]),width))
Share:
20,230
Puneet Sinha
Author by

Puneet Sinha

Data Science manager, Machine learning specialist, python Developer,data analyst,Pyspark,SQL

Updated on January 25, 2022

Comments

  • Puneet Sinha
    Puneet Sinha over 2 years

    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