Back

Formatting to different bases

You can use the format method of a string object to easily convert between different bases:

'b' outputs in binary (base 2).
'o' outputs to oct (base 8).
'd' outputs to denary (base 10).
'x' outputs to hex (base 16) using lowercase letters.
'X' outputs to hex (base 16) using uppercase letters.

For example:

print("The binary form of 35 is {0:b}".format(35))

displays

The binary form of 35 is 100011

Q1. Display in a suitable sentence the binary form of 55.
Q2. Display in a suitable sentence the binary form of 116.
Q3. Display in a suitable sentence the oct form of 73.
Q4. Display in a suitable sentence the hex form of 91 using lower case letters for the hex number.
Q5. Display in a suitable sentence the hex form of 255 using upper case letters for the hex number.
Q6. Display in a suitable sentence the hex form of 255 using upper case letters for the hex number. The number should be displayed in a field 10 characters wide and be right hand justified.
Q7. Display in a suitable sentence the hex form of 255 using upper case letters for the hex number. The number should be displayed in a field 6 characters wide and be left hand justified.
Q8. Display in a suitable sentence the hex form of 255 using upper case letters for the hex number. The number should be displayed in a field 12 characters wide and be center justified.
Q9. Display 289 as a decimal number, in a field 15 characters wide, center justified.
Q10. Test your neighbour. Write your own formatting problems with a correct and fully-checked solution. Then challenge your neighbour to write the code to format the numbers as you want them.

Back