You are on page 1of 8

String formatting

🧵
String formatting
price = 19.99
message = “Your product costs “ + price # Error
String formatting
price = 19.99
message = “Your product costs “ + price # Error

In order to combine strings and numbers, we must format the string


String formatting
price = 19.99
message = “Your product costs “ + price # Error

In order to combine strings and numbers, we must format the string


price = 19.99
message = “Your product costs {}“.format(price)
# Your product costs 19.99
String formatting
price = 19.99
message = “Your product costs “ + price # Error

In order to combine strings and numbers, we must format the string


price = 19.99
message = “Your product costs {}“.format(price)
# Your product costs 19.99

You can add as many numbers as you want


String formatting
price = 19.99
message = “Your product costs “ + price # Error

In order to combine strings and numbers, we must format the string


price = 19.99
message = “Your product costs {}“.format(price)
# Your product costs 19.99

You can add as many numbers as you want


price = 19.99
amount = 3
total = price * amount
message = “For {} products at a price of {}, totaling {}”
print(message.format(amount, price, total))
String formatting
Formatting using indexes
String formatting
Formatting using indexes
price = 19.99
amount = 3
total = price * amount
message = “For {2} products at a price of {0}, totaling {1}”
print(message.format(price, total, amount)

You might also like