Skip to content

Python:Fstring

Python’s f-strings are no secret by now. Introduced in Python 3.6 with PEP 498, they are a better, cleaner, faster, and safer method of interpolating variables, objects, and expressions into strings.

But did you know there is more to f-strings than just inserting variables? There exists a hidden formatting syntax called the Format Mini-Language that allows you to have much greater control over string formatting.

Usage

Regular f-strings

print(f"Hello {item}!")

Output:

Hello World!

Debug Expressions

print(f"{name=}, {age=}")

Output:

name='Claude', age=3

Number Formatting

print(f"Pi: {pi:.2f}")
print(f"Avogadro: {avogadro:.2e}")
print(f"Big Number: {big_num:,}")
print(f"Hex: {num:#0x}")
print(f"Number: {num:09}")

Output:

Pi: 3.14
Avogadro: 6.02e+23
Big Number: 1,000,000
Hex: 0x1a4
Number: 000000420

String Padding

print(f"Left: |{word:<10}|")
print(f"Right: |{word:>10}|")
print(f"Center: |{word:^10}|")
print(f"Center *: |{word:*^10}|")

Output:

Left: |Python    |
Right: |    Python|
Center: |  Python  |
Center *: |**Python**|

Date Formatting

print(f"Date: {now:%Y-%m-%d}")
print(f"Time: {now:%H:%M:%S}")

Output:

Date: 2025-03-10
Time: 14:30:59

Percentage Formatting

print(f"Progress: {progress:.1%}")

Output:

Progress: 75.0%

Example

print(f"{' [ Run Status ] ':=^50}")
print(f"[{time:%H:%M:%S}] Training Run {run_id=} status: {progress:.1%}")
print(f"Summary: {total_samples:,} samples processed")
print(f"Accuracy: {accuracy:.4f} | Loss: {loss:#.3g}")
print(f"Memory: {memory / 1e9:+.2f} GB")

Output:

=================== [ Run Status ] ===================
[11:16:37] Training Run run_id=42 status: 87.4%
Summary: 12,345,678 samples processed
Accuracy: 0.9876 | Loss: 0.0123
Memory: +2.75 GB

You can do things like enable debug expressions, apply number formatting (similar to str.format), add string padding, format datetime objects, and more! All within f-string format specifiers.

See also

Favorite site

References


  1. 14_Advanced_Python_Features_-_Edward_Li's_Blog.pdf