Alternate formatting with #
The # flag asks a formatter for its alternate representation. There is no single universal transformation - the effect depends on the formatting trait being used.
assert_eq!(format!("{:#b}", 42), "0b101010");
assert_eq!(format!("{:#o}", 42), "0o52");
assert_eq!(format!("{:#x}", 42), "0x2a");
assert_eq!(format!("{:#X}", 42), "0x2A");Numeric prefixes
Section titled “Numeric prefixes”For the standard integer base formatters, # adds the conventional prefix:
| Syntax | Prefix |
|---|---|
{:#b} |
0b |
{:#o} |
0o |
{:#x} |
0x |
{:#X} |
0x |
The prefix is part of the formatted width. When alternate formatting is combined with numeric zero padding, zeros are inserted after the prefix and before the digits.
Combine # with width and zero padding
Section titled “Combine # with width and zero padding”Alternate prefixes participate in the total width. For example, "{:#010x}" includes the 0x prefix inside the ten-character minimum width, and zero padding is inserted after the prefix.
That detail matters when you are formatting fixed-width numeric columns or diagnostics. Calculate the width as the width of the entire formatted representation, not just the hexadecimal digits.
Pretty Debug
Section titled “Pretty Debug”# has a different meaning with Debug. {:#?} requests the pretty Debug representation, which derived and standard Debug implementations commonly render with line breaks and indentation.
That output is for inspection, not a stable serialization format. See pretty Debug for the stability caveat and practical use.
Custom formatters
Section titled “Custom formatters”Custom implementations can inspect whether alternate formatting was requested through the Formatter. That means # is a signal to the formatting trait implementation, not a generic post-processing step.
When you are reading an unfamiliar custom formatter, check the trait implementation before assuming what # means.