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
Output:
Debug Expressions
Output:
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:
String Padding
print(f"Left: |{word:<10}|")
print(f"Right: |{word:>10}|")
print(f"Center: |{word:^10}|")
print(f"Center *: |{word:*^10}|")
Output:
Date Formatting
Output:
Percentage Formatting
Output:
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
- Python
- Python:String - Python 문자열 사용방법에 대한 설명.
- Python:Fstring - f-string
- Python:Tstring - t-string
Favorite site
- Python's F-String for String Interpolation and Formatting – Real Python
- Python's Format Mini-Language for Tidy Strings – Real Python
- 7. Input and Output — Python 3.13.3 documentation
- PEP 498 – Literal String Interpolation | peps.python.org
- [추천] 고급 Python 기능들 | GeekNews
References
-
14_Advanced_Python_Features_-_Edward_Li's_Blog.pdf ↩