Other than using %, Python also has the format() command to format strings. The syntax for this command is
"string to be formatted".format(values or variables to be inserted into string, followed by commas)
When we use the format() method, we do not use %s, %f or %d as placeholders. Instead, curly brackets are used.
Example
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('Lenovo', 1299, 1.235235345)
(In this example, there are no defined variables. It is optional to define your data as variables)
Inside the curly bracket, we first write the position of the parameter to use, followed by a colon. After the colon, the formatter is written. There should be not any spaces within the curly brackets.
When we write format('Lenovo', 1299, 1.235235345), we are passing in three parameters to the format() method. Parameters are data that the method needs in order to perform its task. The parameters are 'Lenovo', 1299 and 1.235235245.
The parameter 'Lenovo' has a position of 0,
1299 has a position of 1 and
1.235235245 has a position of 2.
When we write {0:s}, we are asking the interpreter to replace {0:s} with the parameter in position 0 and that it is a string.
When we write {1:d}, we are referring to the parameter in position 1, which is an integer.
When we write {2:4.2f}, we are referring to the parameter in position 2, which is a float and we want it to be formatted with 2 decimal places and a total length of 4.
Output
The price of this Lenovo laptop is 1299 USD and the exchange rate is 1.24 USD to 1 EUR
Instead of formatting the string, we can also write
message = 'The price of this {} laptop is {} USD and the exchange rate is {} USD to 1 EUR'.format('Lenovo', 1299, 1.235235345)
Here we do not need to specify the position of the parameters. The interpreter will replace the curly brackets based on the order of the parameters provided.
Output
The price of this Lenovo laptop is 1299 USD and the exchange rate is 1.235235245 USD to 1 EUR
No comments:
Post a Comment