Learn Python
>>> io_formatting.string_formatting

String Formatting (f-strings, format(), %) in Python

#concept

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.

#how it works
1

f-strings

Prefix the string with f, then embed any expression directly inside curly braces.

2

.format()

Write {} placeholders in the string, then call .format(value1, value2, ...) to fill them in order.

3

The % operator

Use placeholders like %s and %d, then supply values after a % sign.

4

Format specifiers work in all three

Things like decimal precision β€” f"{price:.2f}" formats to exactly two decimal places.

5

f-strings are the modern default

Most readable and fastest to run, and generally preferred in new Python code.

#example
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))
Output
Hi Ada, total is 20.00
Hi Ada, total is 20.00
Hi Ada, total is 20.00
1The f-string embeds name and price directly, with :.2f formatting price to exactly two decimal places (rounding 19.999 up to 20.00).
2.format() reaches the identical result using empty {} placeholders, filled in order by the arguments passed to .format().
3The % operator does the same using %s for a string and %.2f for a float with two decimal places.
4All three lines print an identical result β€” the difference is purely in syntax and style, not capability.
#use cases
Building any user-facing message that combines text and data, from log lines to UI labels
Formatting numbers for money, percentages, or fixed decimal places in reports
Reading and maintaining older Python code that still uses .format() or %
Choosing f-strings by default in new code, for their readability and speed

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself β€” building beats watching.