Rust pad and align strings with width and fill
To pad a Rust string, put the minimum width in the format specification and choose an alignment. Use {:>8} for left padding, {:<8} for right padding, or {:^8} to center the value. Add a fill character immediately before the alignment operator when spaces are not what you want.
let value = "rust";
assert_eq!(format!("|{value:<8}|"), "|rust |");
assert_eq!(format!("|{value:^8}|"), "| rust |");
assert_eq!(format!("|{value:>8}|"), "| rust|");
assert_eq!(format!("|{value:.^8}|"), "|..rust..|");
let width = 8;
assert_eq!(format!("|{value:>width$}|"), "| rust|");How to pad a string in Rust
Section titled “How to pad a string in Rust”For a string such as "rust" and a width of eight:
| Syntax | Result | Use |
|---|---|---|
{:<8} |
rust |
pad on the right |
{:^8} |
rust |
center with space fill |
{:>8} |
rust |
pad on the left |
{:.^8} |
..rust.. |
center with custom fill |
Width is a minimum, not a fixed output length. If the formatted value is already longer than the requested width, Rust does not truncate it.
Alignment operators
Section titled “Alignment operators”Rust uses three alignment characters:
| Syntax | Meaning |
|---|---|
< |
left-align |
^ |
center |
> |
right-align |
The width follows the alignment, so {:>8} means “format this value in at least eight columns and place padding on the left.”
For non-numeric values, the default fill is a space and the default alignment is left. Numeric formatters default to right alignment.
Dynamic width
Section titled “Dynamic width”The width does not have to be hard-coded. A usize formatting argument can provide it dynamically:
{value:>width$}That is useful for table-like output where a column width is calculated or configured elsewhere. The checked example above verifies the captured-width form.
See arguments and captured variables for the wider parameter-selection rules.
Custom fill
Section titled “Custom fill”A custom fill character appears immediately before the alignment character:
{:.^8}That means “center within width 8 and use . for padding.” The fill character and alignment are a pair - a character in that position is only interpreted as fill when an alignment operator follows it.
Width is not precision
Section titled “Width is not precision”Width adds padding when output is too short. Precision can shorten some representations and controls decimal places for floating-point formatting.
If you need a fixed-looking table column, width and alignment are usually the first tools to reach for. If you need to limit a string or control floating-point decimal places, use precision.
Numeric zero padding is special
Section titled “Numeric zero padding is special”For numbers, 0 is not just a normal fill character. The zero-padding flag is sign-aware and interacts with prefixes such as 0x. Use signs and zero padding when a sign or numeric prefix is involved instead of treating 0 as ordinary fill.