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

(singke) #1

Python replaces the {veggie} named placeholder with the value assigned to the veggie name in
the format() expression. If you have more than one named value in the expression, you just
separate them using commas, as shown here:


Click here to view code image


>>> vegetable = 'carrots'
>>> fruit = 'bananas'
>>> print('Fruit: {fruit}, Veggie: {veggie}'.format(fruit=fruit,
veggie=vegetable))
Fruit: bananas, Veggie: carrots
>>>

You can also assign string and numeric values directly to the named placeholder, as in this example:


Click here to view code image


>>> print('My favorite fruit is a {fruit}.'.format(fruit='banana'))
My favorite fruit is a banana.
>>>

You might be thinking that so far all this does is add an extra layer of complexity to displaying string
values, with no additional purpose. However, the true power of the format() function comes in its
formatting capabilities. The next section examines those capabilities.


Formatting Numbers


The true power of the format() function comes into play when you need to display numeric values
in your output. By default, Python treats numeric values as strings in the output generated by the
print() function. That can lead to some pretty ugly printouts, as there’s no control over things such
as how many decimal places to display or whether to use scientific notation to display large values.


The format() function provides a wide array of formatting codes for you to specify exactly how
Python displays the values. You just place the formatting codes within the placeholder braces in the
string value, separated by a colon from the placeholder number or name.


You can use different formatting codes, based on the type of data you want to display. Here’s a quick
example to demonstrate:


Click here to view code image


>>> total = 3.4999999
>>> print('The total is {0:.2f}'.format(total))
The total is 3.50
>>>

This formatting code tells Python to round the floating-point value to two decimal places for you.
Now that’s handy! The following sections walk through the different codes you can use, based on the
data type of the value you need to display.


Integer Values


Displaying integer values doesn’t usually involve too much formatting. By default, Python just
displays integer values using the decimal format, which is usually just fine.


However, you can spice things up by specifying formatting codes to have Python convert the integer
value to another base (such as octal or hexadecimal) for the display automatically. Table 10.4 lists
the integer-formatting codes that are available.

Free download pdf