Text

String Formatting

f-strings turn values into readable text at the point of use.

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.5

Format 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.5
FORMAT SPECalignsignwidth,.prectype{:>6,.2f}
The format spec is a railroad of named optional fields: alignment, sign, width, precision, type.

The 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.5

Notes

See also

Run the complete example

Example code

Expected output

Ada scored 9.5
 1 | Ada      | 009.5
score = 9.5

Execution time appears here after you run the example.