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

(singke) #1
the v3 format() function formatting codes. If you need to use the Python v2
formatting method, refer to the Python documentation at http://www.python.org.

The format() Function


The format() function is the most complicated of the built-in Python string functions. However,
once you get the hang of it, you’ll find yourself using it in lots of places in your scripts to help make
your output more user friendly.


This is the syntax for the format() function:


string.format(expression)

There are two parts to using the format() function. The string component is the output string
that you want to display, and the expression component defines what variables to embed in the
output.


In the output string, you also need to embed placeholders within the string where you want the
variable values from the expression to appear. There are two types of placeholders you can use:


Positional placeholders
Named placeholders

The next two sections discuss each of these types of placeholders.


Positional Placeholders


Positional placeholders create spots in the output string to insert variable values by using numeric
index values representing the order of the variables in the expression. To identify the placeholders,
you put the index value within braces inside the string text. While this might sound confusing, it’s
actually pretty straightforward. Here’s an example:


Click here to view code image


>>> test1 = 10
>>> test2 = 20
>>> result = test1 + test2
>>> print('The result of adding {0} and {1} is {2}'.format(test1, test2,
result))
The result of adding 10 and 20 is 30
>>>

Python inserts the value of each variable in the expression list in its associated positional
placeholder. The test1 variable value is placed in the {0} location, the test2 variable value is
placed in the {1} location, and the result variable value is placed in the {2} location.


Named Placeholders


Instead of using index values, for the named placeholder method, you assign names to each variable
value you want placed in the output string. You assign the names to each of the replacement values in
the expression list and then use the names in the placeholders in the output string, as in this example:


Click here to view code image


>>> vegetable = 'carrots'
>>> print('My favorite vegetable is {veggie}'.format(veggie=vegetable))
My favorite vegetable is carrots
>>>
Free download pdf