Loading lessons...
String Formatting
String Formatting
Formatting inserts values into a string. The modern way is f-strings; the older way is .format().
The % operator (old style)
price = 49
txt = "The price is %d dollars"
print(txt % price) # The price is 49 dollars
%d is a placeholder for an integer. Other codes: %f for float, %s for string.
The format() method
txt = "The price is {} dollars"
print(txt.format(price)) # The price is 49 dollars
Multiple placeholders
item = "apple"
count = 3
price = 49.95
txt = "I want {} pieces of item {} for {} dollars"
print(txt.format(count, item, price))
Indexed placeholders
txt = "I have a {carname}, it is a {model}."
print(txt.format(carname="Ford", model="Mustang"))
Formatting numbers with format()
price = 49
txt = "The price is {:.2f} dollars"
print(txt.format(price)) # The price is 49.00 dollars
Formatting numbers with f-strings
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt) # The price is 59.00 dollars
Alignments and separators
:>right-align,:<left-align,:^center.:,thousands separators.
print(f"{1234567:,}") # 1,234,567
print(f"{'hi':^10}") # centered in 10 spaces
TL;DR
%d,%f,%sare old-style placeholders..format()uses{}placeholders.- f-strings are the modern, recommended way.
- Specifiers like
:.2fand:,format numbers.