In this page, we will discuss about formatting with the % operator and the format() function will be discussed later.
Syntax
"string to be formatted" %(values or variables to be inserted into string, separated by commas)
There are three parts to this syntax. First the string to be formatted is written in quotes. Then the % symbol is written. Finally, there is a pair of round brackets () within which values or variables are written to be inserted into the string. This round brackets with values inside is called a tuple, a data type which we will discuss in the future.
The % sign is separately inserted with s, d and f for string, integer and float respectively.
1. %s is used for string
2. %d is used for integers
3. %f is used for float (length of the float, then a dot and then decimal places - note that the length of the float includes the decimal).
Example
brand = 'Lenovo'
price = 1299
exchangeRate = 1.235235245
message = 'The price of this %s laptop is %d USD and the exchange rate is %4.2f USD to 1 EUR' %(brand, price, exchangeRate)
print (message)
Output
The price of this Lenovo laptop is 1299 USD and the exchange rate is 1.24 USD to 1 EUR
Code analysis
In the example above, the string 'The price of this %s laptop is %d USD and the exchange rate is %4.2f USD to 1 EUR' is the string that we want to format. We use the %s, %d and %4.2f formatters as placeholders.
The %s formatter is used to represent a string while the %d formatter represents an integer and the %f formatter is used to format floats.
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 example, "%5d" %(123) will give us " 123" with 2 spaces in front and a total length of 5.
There is additional information in the code for the %f formatter for floats. The number before the decimal point tells us the length of the given float number and the number after the decimal point tells the number of decimal places in the float.
Here it is formatted 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 it as %7.2f, which will give us " 1.24" with 2 decimal places, 3 spaces in front and a total length of 7. The decimal point also contributes to the length. The 4 in 4.2 refers to the three numbers with the decimal point included.
These placeholders will be replaced with the variable brand, the variable price and the variable exchangeRate respectively, as indicated in the round brackets. If this code is entered and run, the output will be
The price of this Lenovo laptop is 1299 USD and the exchange rate is 1.24 USD to 1 EUR
No comments:
Post a Comment