Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
TABLE 10.4 Integer-Formatting Codes

There’s nothing tricky about any of these codes. You just include them in the placeholder to output the
integer value in that format, as shown here:


Click here to view code image


>>> test1 = 154
>>> print('Binary: {0:b}'.format(test1))
Binary: 10011010
>>> print('Octal: {0:o}'.format(test1))
Octal: 232
>>> print('Hex: {0:x}'.format(test1))
Hex: 9a
>>>

Now you’re starting to see some of the built-in power of using the format() function for your
output!


Floating-Point Values


Displaying floating-point values can be somewhat of a pain. Not only do you have to worry about
small values with several places past the decimal point, you may also have to worry about very large
numbers. To get your floating-point values to display in a user-friendly manner, you can use the
floating-point formatting codes for the format() function. Table 10.5 shows what’s available for
you to use.


TABLE 10.5 Floating-Point Formatting Codes

With floating-point values, besides the formatting code, you can also specify the number of decimal
places Python should round the value to. Here’s an example of that:

Free download pdf