String Formatting (f-strings, format(), %) in Python
String formatting means building a string with other values embedded inside it. Python has three main ways to do this: f-strings (the modern, recommended approach β prefix a string with f and embed expressions directly in curly braces), the .format() method (write {} placeholders, then fill them in with .format()), and the older % operator, borrowed from C-style formatting. All three exist in real code, but f-strings are the clearest and fastest to write today.
f-strings
Prefix the string with f, then embed any expression directly inside curly braces.
.format()
Write {} placeholders in the string, then call .format(value1, value2, ...) to fill them in order.
The % operator
Use placeholders like %s and %d, then supply values after a % sign.
Format specifiers work in all three
Things like decimal precision β f"{price:.2f}" formats to exactly two decimal places.
f-strings are the modern default
Most readable and fastest to run, and generally preferred in new Python code.
name = "Ada"price = 19.999Β print(f"Hi {name}, total is {price:.2f}")print("Hi {}, total is {:.2f}".format(name, price))print("Hi %s, total is %.2f" % (name, price))Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself β building beats watching.