Text
String Formatting
An f-string evaluates expressions inside braces and inserts their string form into the surrounding text. This is clearer than joining several converted values by hand.
Source
name = "Ada"
score = 9.5
rank = 1
message = f"{name} scored {score}"
print(message)Output
Ada scored 9.5Format specifications after : control display without changing the underlying values. Here the rank is right-aligned, the name is left-aligned, and the score is padded to one decimal place.
Source
row = f"{rank:>2} | {name:<8} | {score:05.1f}"
print(row)Output
1 | Ada | 009.5The debug form with = is useful while learning or logging because it prints both the expression and the value.
Source
print(f"{score = }")Output
score = 9.5Notes
- Use
f"..."strings for most new formatting code. - Expressions inside braces are evaluated before formatting.
- Format specifications after
:control alignment, width, padding, and precision.
See also
Run the complete example
Expected output
Ada scored 9.5
1 | Ada | 009.5
score = 9.5
Execution time appears here after you run the example.