- Get link
- X
- Other Apps
String Format
In the chapter on Python Variables, we discovered that it is not possible to mix strings and numbers together, as shown in the following example:
Example
weight = 60
line = "I'm Abc, my weight is " + weight
print(line)
line = "I'm Abc, my weight is " + weight
print(line)
However, there is a clever way to combine strings and numbers in Python by utilizing the format() method!
You can use the format() method to insert values into a string by placing them inside curly braces {}:
Example
To insert numbers into strings, you can utilize the format() method:
weight = 60
line = "I'm Abc, my weight is {}"
print(line.format(age))
Note: The format() method allows you to include an unlimited number of arguments, which will be placed in the corresponding placeholders within the string:
Example
quantity = 4
item_no = 150
price = 65.67
my_order = "He desires to acquire {} item {} for the price of {} dollars"
print(my_order.format(quantity, item_no, price))
item_no = 150
price = 65.67
my_order = "He desires to acquire {} item {} for the price of {} dollars"
print(my_order.format(quantity, item_no, price))
To ensure that the arguments are placed in the correct placeholders, you can use index numbers like {0} within the format() method. This way, each argument will be assigned to the designated placeholder based on its corresponding index number:
Example
quantity = 4
item_no = 150
price = 65.67
my_order = "He wishes to pay {2} for {0} piece of item {1}."
print(my_order.format(quantity, item_no, price))
item_no = 150
price = 65.67
my_order = "He wishes to pay {2} for {0} piece of item {1}."
print(my_order.format(quantity, item_no, price))
Comments
Post a Comment