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.

MethodSyntaxDescription
Expression Evalf"{x * 2}"Evaluates basic Python variables or logic directly.
Decimal Precisionf"{pi:.2f}"Formats variable float values to show exactly 2 decimal places.
Thousands Commaf"{num:,}"Puts commas in numbers as thousands grouping separators.
Percentage Conversionf"{ratio:.1%}"Multiplies by 100 and shows value as a percentage with 1 decimal place.

Alignment, Padding & Numbers

Text spacing controls and number bases.

MethodSyntaxDescription
Left / Right Alignf"{name:<10}" / f"{name:>10}"Pads output text to a width of 10, aligned left or right.
Center Alignf"{text:^10}"Pads output text to a width of 10, centering the text.
Char Paddingf"{num:*^10}"Pads with asterisks instead of blank spaces.
Base Formattingf"{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.