Skip to content

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.

EXAMPLE: CI-CHECKEDTEST ASSERTED · examples/format-output/src/format_pages.rs#page-width-alignment-fill
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|");

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.

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.

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.

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 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.

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.