Learn Python - 28

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

round

brackets. If we run the code, we’ll get the output below.



The price of this Apple laptop is 1299 USD and the
exchange rate is 1.24 USD to 1 EUR

The %s formatter is used to represent a string (“Apple” in this case) while
the %d formatter represents an integer (1299). If we want to add spaces
before an integer, we can add a number between % and d to indicate the
desired length of the string. For instance “%5d” %(123) will give us “
123” (with 2 spaces in front and a total length of 5).

The %f formatter is used to format floats (numbers with decimals). Here
we format it as %4.2f where 4 refers to the total length and 2 refers to 2
decimal places. If we want to add spaces before the number, we can
format is as %7.2f, which will give us “ 1.24” (with 2 decimal places, 3
spaces in front and a total length of 7).

Formatting Strings using the format() method

In addition to using the % operator to format strings, Python also provides
us with the format() method to format strings. The syntax is

“string to be formatted”.format(values or variables to
be inserted into string, separated by commas)

When we use the format method, we do not use %s, %f or %d as
placeholders. Instead we use curly brackets, like this:

message = ‘The price of this {0:s} laptop is {1:d} USD
and the exchange rate is {2:4.2f} USD to 1
EUR’.format(‘Apple’, 1299, 1.235235245)

Inside the curly bracket, we first write the position of the parameter to

You might also like