Python f-String Formatting Cheat Sheet
Guide to Python f-string formatting. Master decimal precision, alignment, date formatting, and expression evaluation.
Expressions & Floating Point Precision
Evaluating variables and decimal point restrictions directly in template strings.
| Method | Syntax | Description |
|---|---|---|
| Expression Eval | f"{x * 2}" | Evaluates basic Python variables or logic directly. |
| Decimal Precision | f"{pi:.2f}" | Formats variable float values to show exactly 2 decimal places. |
| Thousands Comma | f"{num:,}" | Puts commas in numbers as thousands grouping separators. |
| Percentage Conversion | f"{ratio:.1%}" | Multiplies by 100 and shows value as a percentage with 1 decimal place. |
Alignment, Padding & Numbers
Text spacing controls and number bases.
| Method | Syntax | Description |
|---|---|---|
| Left / Right Align | f"{name:<10}" / f"{name:>10}" | Pads output text to a width of 10, aligned left or right. |
| Center Align | f"{text:^10}" | Pads output text to a width of 10, centering the text. |
| Char Padding | f"{num:*^10}" | Pads with asterisks instead of blank spaces. |
| Base Formatting | f"{num:x}" / f"{num:b}" | Converts decimal integer to hexadecimal (x) or binary (b) representation. |
Frequently Asked Questions
Can I evaluate function calls inside f-strings?
Yes, you can include any valid Python expressions, including function calls and arithmetic, inside the curly braces {} of an f-string.
How do you escape curly braces in an f-string?
Double the braces, e.g., {{ and }} to print literal curly braces.
Keep Learning
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Functions
Master Python functions. Learn how to write reusable code using def, define arguments, return values, and understand scope locally and globally.
How to Read a File in Python
Learn how to read files in Python. Master the with open statement, readline, readlines, and safely handling file exceptions.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.