Text

String Formatting

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

Formatted string literals, or f-strings, exist because programs constantly need to turn values into human-readable text. They keep the expression next to the words it explains.

Format specifications after : control presentation details such as width, alignment, padding, and precision. This separates the value being computed from the way it should be displayed.

Use f-strings for most new formatting code. They relate directly to expressions: anything inside braces is evaluated, then formatted into the surrounding string.

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 05.1f zero-pads the score to a width of five characters with one decimal place.

Source

row = f"{rank:>2} | {name:<8} | {score:05.1f}"
print(row)

Output

 1 | Ada      | 009.5
The format spec is a railroad of optional stations in a fixed order; this cell's 05.1f visits zero-pad, width, precision and type and bypasses the rest.

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.