Python f-string format specifier: syntax and examples
python f string format specifier: Learn how to use Python f-string format specifiers for alignment, numeric precision, grouping, and more with practical examples.
The python f string format specifier is the part of an f-string that controls how a value is converted to text. It appears after a colon inside the curly braces and can set width, alignment, numeric precision, and other presentation rules. This article explains the format specifier syntax and shows how to apply it to common formatting tasks.
The Format Specifier Syntax
An f-string is a string literal prefixed with f or F. Inside the braces, you write an expression followed by an optional format specifier:
value = 42 print(f"{value:>10}")
The format specifier itself follows the colon. Its general structure is:
[[fill]align][sign][#][0][width][grouping][.precision][type]
Each part is optional, and they must appear in this order. The fill and align parts control how the value occupies its width. The sign controls how positive and negative numbers are displayed. The # enables alternate form for some types. The 0 pads with zeros. width is the minimum field width. grouping adds separators. .precision sets the number of digits after the decimal point. type selects the presentation type, such as d, f, e, or x.
Understanding this structure helps you read and write format specifiers without memorizing each option separately.
Alignment, Width, and Fill
By default, a value is left-aligned within its width for strings and right-aligned for numbers. You can override this with with <, >, or ^ for left, right, and center alignment respectively. The fill character precedes the alignment character and is a space by default.
name = "Ada" print(f"{name:<10}|") print(f"{name:>10}|") print(f"{name:^10}|") print(f"""{name:*^10}\