# Rust format specifier grammar

> Read the exact order of fill, alignment, sign, alternate, zero, width, precision, and type in a Rust format specification.

HTML: https://rustprint.com/reference/format-specifier-grammar/

When several formatting controls appear in one field, their order is fixed. Rust's standard grammar is the authoritative answer.

```text
format_string := text [ maybe_format text ] *
maybe_format := '{' '{' | '}' '}' | format
format := '{' [ argument ] [ ':' format_spec ] [ ws ] * '}'
argument := integer | identifier

format_spec := [[fill]align][sign]['#']['0'][width]['.' precision][type]
fill := character
align := '<' | '^' | '>'
sign := '+' | '-'
width := count
precision := count | '*'
type := '?' | 'x?' | 'X?' | 'o' | 'x' | 'X' | 'p' | 'b' | 'e' | 'E'
count := parameter | integer
parameter := argument '$'
```

## Read a dense specifier left to right

Consider `{value:#010x}`. `value` selects the argument, `:` starts the format specification, `#` requests the alternate hexadecimal form, `0` enables sign-aware numeric zero padding, `10` is the minimum width, and `x` selects `LowerHex`.

**Alternate hexadecimal with zero padding and width**

```rust
let value = 27;
assert_eq!(format!("{value:#010x}"), "0x0000001b");
```

The resulting width includes the `0x` prefix.

## The order is syntax, not style

You cannot arbitrarily rearrange the flags. Fill only has meaning when followed by an alignment operator, the sign comes before `#` and `0`, width comes before precision, and the type suffix comes last.

For normal work, start from the feature you need rather than assembling punctuation from memory. Use [arguments and capture](/format/arguments-and-capture/index.md), [width, alignment, and fill](/format/width-alignment-fill/index.md), [precision](/format/precision/index.md), [signs and zero padding](/format/signs-and-zero-padding/index.md), [alternate formatting](/format/alternate-format/index.md), or [formatting traits](/reference/formatting-traits/index.md) for the individual pieces.

Use this page as the final lookup when those pieces are combined into one specification.

## Sources

- [std::fmt syntax](https://doc.rust-lang.org/std/fmt/#syntax)

## Related RustPrint guides

- [Rust format strings - syntax, width, precision, and traits](/format/format-strings/index.md): Read Rust format strings from {} through argument capture, width, precision, alignment, escaping, and formatting traits.
- [Rust formatting traits - Display, Debug, hex, binary, and more](/reference/formatting-traits/index.md): Map Rust format syntax such as {}, {:?}, {:x}, {:b}, and {:e} to the std::fmt traits Display, Debug, LowerHex, Binary, and LowerExp.
- [Rust format arguments: positional, named, and captured variables](/format/arguments-and-capture/index.md): Use implicit, positional, named, and captured arguments in Rust format strings, including println! with captured variables and how argument selection ends at the colon.
