Zig Format Strings
Whenever you print in Zig, you write a format string with placeholders like {d} and {s}, and a list of values to fill in. The same rules work everywhere: std.debug.print, a stdout writer’s print, and the functions that build strings in memory. This page goes through every placeholder you’ll need, how to line things up in columns, how to print structs, optionals and errors, and how to format into a string instead of the screen.
Every example was run on Zig 0.17.1. Formatting changed quite a bit in 0.15, so if you find older code online that uses {} everywhere, it may not compile anymore. 0.17 added a few smaller things, like {q} for quoted strings, which you’ll meet below.
How a format string works
Section titled “How a format string works”A print call takes two things: the format string, and a tuple (a list) of values written as .{ ... }. Each {...} in the string takes the next value from the list, in order:
const std = @import("std");
pub fn main() void { const name = "Ada"; const age = 36; std.debug.print("{s} is {d} years old.\n", .{ name, age });}Output:
Ada is 36 years old.The letter inside the braces is the specifier: it says how to show the value. s means string and d means decimal number.
The format string has to be known when the program compiles, and Zig checks it then. A placeholder without a value is a compile error, not a crash or garbage output like printf in C:
const std = @import("std");
pub fn main() void { std.debug.print("{d} and {d}\n", .{1});}lib/std/Io/Writer.zig:803:13: error: too few arguments @compileError("too few arguments"); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~The error points into the standard library, because that’s where the check lives. Look at the message itself, and further down at the referenced by: lines, which lead back to your print call.
Extra values with no placeholder are an error too (unused argument). And the values always go in a tuple, even when there’s just one: .{x}, not x. With no values at all, you still write .{}.
The specifiers you’ll use most
Section titled “The specifiers you’ll use most”| Specifier | Shows | Example | Prints |
|---|---|---|---|
{d} |
a number in decimal | {d} with 42 |
42 |
{s} |
a string | {s} with "hi" |
hi |
{c} |
a byte as a character | {c} with 'A' |
A |
{u} |
a Unicode code point as UTF-8 | {u} with 0xE9 |
é |
{x} / {X} |
hexadecimal, lower / upper case | {x} with 255 |
ff |
{b} |
binary | {b} with 5 |
101 |
{o} |
octal | {o} with 8 |
10 |
{e} |
a float in scientific notation | {e} with 1234.5 |
1.2345e3 |
{any} |
any value, in its default form | {any} with a struct |
.{ .x = 3, .y = -4 } |
Here they are in one program:
const std = @import("std");
pub fn main() void { std.debug.print("decimal: {d}\n", .{42}); std.debug.print("string: {s}\n", .{"hello"}); std.debug.print("char: {c}\n", .{'A'}); std.debug.print("hex: {x} {X}\n", .{ 255, 255 }); std.debug.print("binary: {b}\n", .{5}); std.debug.print("octal: {o}\n", .{8}); std.debug.print("float: {d} {e}\n", .{ 1234.5, 1234.5 });}Output:
decimal: 42string: hellochar: Ahex: ff FFbinary: 101octal: 10float: 1234.5 1.2345e3A few things worth knowing:
- In Zig,
'A'is just the number 65.{c}shows it as a letter,{d}would show65. {x}also works on strings:{x}with"abc"prints the bytes in hex,616263.{d}works for both whole numbers and floats.
Strings need {s}
Section titled “Strings need {s}”Numbers and true/false also print with empty braces {}. Strings don’t. In Zig a string is a list of bytes, and Zig won’t guess whether you want text or numbers:
const std = @import("std");
pub fn main() void { std.debug.print("{}\n", .{"hello"});}lib/std/Io/Writer.zig:1503:21: error: cannot format slice without a specifier (i.e. {s}, {x}, {b64}, or {any}){any} won’t give you text either. It shows the bytes as numbers:
const std = @import("std");
pub fn main() void { std.debug.print("{s} vs {any}\n", .{ "abc", "abc" });}Output:
abc vs { 97, 98, 99 }When you’re debugging and want to see exactly what’s in a string, use {q}. It prints the string in double quotes, with escapes like \n for the characters you can’t see. That makes stray spaces and newlines easy to spot:
const std = @import("std");
pub fn main() void { const name = "Ada \n"; std.debug.print("name: {s}!\n", .{name}); std.debug.print("name: {q}!\n", .{name});}Output:
name: Ada!name: "Ada \n"!With {s} the hidden newline breaks the line and the space at the end is invisible. With {q} you can see both. (Zig 0.16 rejects {q} on strings, so this one needs 0.17.)
Width and alignment
Section titled “Width and alignment”Put a : after the specifier, then a width, to make a value take up at least that many characters. Add <, ^ or > before the width to align it left, center or right:
const std = @import("std");
pub fn main() void { std.debug.print("[{d:6}]\n", .{42}); std.debug.print("[{d:<6}]\n", .{42}); std.debug.print("[{d:^6}]\n", .{42}); std.debug.print("[{d:>6}]\n", .{42}); std.debug.print("[{s:<6}]\n", .{"zig"}); std.debug.print("[{s:6}]\n", .{"zig"});}Output:
[ 42][42 ][ 42 ][ 42][zig ][ zig]The square brackets are just there so you can see the spaces.
Width counts bytes, not letters. Letters like é take two bytes in UTF-8, so a word with accents gets less padding than you’d expect. For lining up plain ASCII text and numbers it works fine.
Fill characters and zero padding
Section titled “Fill characters and zero padding”Before the alignment, you can put a fill character to use instead of spaces. The alignment is required when you use a fill, otherwise Zig would read the fill as part of the width.
const std = @import("std");
pub fn main() void { std.debug.print("{d:0>5}\n", .{42}); std.debug.print("{d:*^9}\n", .{42}); std.debug.print("{s:.<12}{d}\n", .{ "Chapter 1", 7 }); std.debug.print("{s:-<20}\n", .{""});}Output:
00042***42****Chapter 1...7--------------------{d:0>5} is the classic “pad with zeros to 5 digits”. The last line prints an empty string padded with -: a quick way to draw a line.
Precision for floats
Section titled “Precision for floats”After the width, a . and a number sets how many digits come after the decimal point:
const std = @import("std");
pub fn main() void { const pi = 3.14159; std.debug.print("{d}\n", .{pi}); std.debug.print("{d:.2}\n", .{pi}); std.debug.print("{d:.0}\n", .{pi}); std.debug.print("[{d:8.2}]\n", .{pi}); std.debug.print("[{d:0>8.3}]\n", .{pi}); std.debug.print("{e:.2}\n", .{123456.0});}Output:
3.141593.143[ 3.14][0003.142]1.23e5The order is always {specifier:fill alignment width.precision}, and you can leave out the parts you don’t need. {d:8.2} is “width 8, 2 decimals”.
Hex and binary with padding
Section titled “Hex and binary with padding”Width and fill work with {x} and {b} too, which is handy for colors, bytes and bit flags:
const std = @import("std");
pub fn main() void { const r = 255; const g = 128; const b = 0; std.debug.print("#{x:0>2}{x:0>2}{x:0>2}\n", .{ r, g, b }); std.debug.print("0x{X:0>8}\n", .{48879}); std.debug.print("{b:0>8}\n", .{10});}Output:
#ff80000x0000BEEF00001010Without the 0>2, 0 would print as just 0 and the color would come out as #ff800.
Printing literal braces
Section titled “Printing literal braces”To print a { or } itself, write it twice:
const std = @import("std");
pub fn main() void { std.debug.print("{{ and }}\n", .{}); std.debug.print("set = {{{d}, {d}}}\n", .{ 1, 2 });}Output:
{ and }set = {1, 2}In {{{d}, {d}}}, the first {{ is a literal brace, then {d} is a placeholder, and at the end }} is a literal brace again.
Picking arguments by position or name
Section titled “Picking arguments by position or name”Normally placeholders take values in order. You can also give a position (starting at 0) before the specifier, or a name in square brackets if you pass a struct with named fields instead of a tuple:
const std = @import("std");
pub fn main() void { std.debug.print("{1s} {0s}\n", .{ "world", "hello" }); std.debug.print("{0s}, {0s}, {0s}!\n", .{"again"}); std.debug.print("{[name]s} is {[age]d}\n", .{ .name = "Ana", .age = 30 });}Output:
hello worldagain, again, again!Ana is 30Positions let you use one value several times. Names make long format strings easier to read.
Structs, arrays and slices
Section titled “Structs, arrays and slices”{any} prints structs, arrays and slices in a readable default form. It’s what you’ll reach for while debugging:
const std = @import("std");
const Point = struct { x: i32, y: i32 };
pub fn main() void { const p = Point{ .x = 3, .y = -4 }; const scores = [_]i32{ 90, 75, 82 }; const some: []const i32 = scores[0..2]; std.debug.print("{any}\n", .{p}); std.debug.print("{any}\n", .{scores}); std.debug.print("{any}\n", .{some});}Output:
.{ .x = 3, .y = -4 }{ 90, 75, 82 }{ 90, 75 }{d} doesn’t work on an array or slice; it’s for single numbers. Use {any}, or loop over the items and print each one with the format you want.
There’s one trap: a struct field that holds text is printed as numbers, because {any} shows strings as bytes:
const std = @import("std");
const User = struct { id: u32, name: []const u8 };
pub fn main() void { const u = User{ .id = 1, .name = "Ana" }; std.debug.print("{any}\n", .{u});}Output:
.{ .id = 1, .name = { 65, 110, 97 } }The fix is to print the fields yourself ({s} for u.name), or give the struct its own format method, which is next.
Your own format method with {f}
Section titled “Your own format method with {f}”If a struct has a method called format, the {f} placeholder calls it. You decide exactly how the value looks:
const std = @import("std");
const Point = struct { x: i32, y: i32,
pub fn format(self: Point, writer: *std.Io.Writer) std.Io.Writer.Error!void { try writer.print("({d}, {d})", .{ self.x, self.y }); }};
pub fn main() void { const p = Point{ .x = 3, .y = -4 }; std.debug.print("point: {f}\n", .{p}); std.debug.print("raw: {any}\n", .{p});}Output:
point: (3, -4)raw: .{ .x = 3, .y = -4 }The method gets the value and a writer, and writes whatever it likes with writer.print. The return type std.Io.Writer.Error!void means “nothing, or a write error”. Methods are explained in Zig Struct Methods.
Optionals and errors
Section titled “Optionals and errors”An optional (?T) is a value that might be missing (null). You’ll learn them in Zig Optionals. To print one, use {?} plus the specifier for the value inside, or {any}:
const std = @import("std");
pub fn main() void { const age: ?u32 = 30; const nickname: ?[]const u8 = null; std.debug.print("age: {?d}\n", .{age}); std.debug.print("nickname: {?s}\n", .{nickname}); std.debug.print("with any: {any}\n", .{age});}Output:
age: 30nickname: nullwith any: 30Plain {d} on an optional is a compile error (invalid format string 'd' for type '?u32'), so Zig makes you notice that the value might be missing.
Errors print with {any} (or {}) as error.Name. {t} prints just the name, which reads better in messages. {t} works on enums too:
const std = @import("std");
const Color = enum { red, green, blue };
pub fn main() void { const err = error.FileNotFound; std.debug.print("{any}\n", .{err}); std.debug.print("failed: {t}\n", .{err});
const c = Color.green; std.debug.print("{t} {any}\n", .{ c, c });
const result: anyerror!u32 = error.OutOfMemory; std.debug.print("{!d}\n", .{result});}Output:
error.FileNotFoundfailed: FileNotFoundgreen .greenerror.OutOfMemory{!d} is for an error union (a value or an error, covered in Zig Errors): it prints the value with {d} if there is one, or the error if not.
Formatting into a string
Section titled “Formatting into a string”Sometimes you want the formatted text as a string, to store it, pass it on or write it somewhere later. These functions use the same format strings:
std.mem.print(&buffer, fmt, args)writes into a buffer you provide and returns the part it used. No memory is allocated. If the text doesn’t fit, it returnserror.NoSpaceLeft.allocator.print(fmt, args)allocates exactly enough memory for the result. You mustfreeit when you’re done.std.fmt.comptimePrint(fmt, args)builds the string at compile time, for values that are known then.
The first two got new homes in Zig 0.17. Older code calls them std.fmt.bufPrint and std.fmt.allocPrint. Those still work in 0.17.1, but they’re deprecated and will go away, so use the new names in new code.
const std = @import("std");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa;
var buffer: [32]u8 = undefined; const line = try std.mem.print(&buffer, "x = {d}, y = {d}", .{ 3, 4 }); std.debug.print("{s}\n", .{line});
const msg = try gpa.print("{s} scored {d} points", .{ "Ana", 42 }); defer gpa.free(msg); std.debug.print("{s} ({d} bytes)\n", .{ msg, msg.len });
var tiny: [4]u8 = undefined; if (std.mem.print(&tiny, "{d}", .{123456})) |text| { std.debug.print("fits: {s}\n", .{text}); } else |err| { std.debug.print("didn't fit: {t}\n", .{err}); }
const version = std.fmt.comptimePrint("v{d}.{d}", .{ 0, 17 }); std.debug.print("{s}\n", .{version});}Output:
x = 3, y = 4Ana scored 42 points (20 bytes)didn't fit: NoSpaceLeftv0.17This program uses a few things from later lessons: init.gpa is an allocator handed to main (see Zig Allocators), defer gpa.free(msg); frees the memory when main ends (see Zig Defer), and if ... else |err| handles the error from std.mem.print. The pattern to remember: std.mem.print when you know the maximum size, allocator.print when you don’t (and then always free).
Quick reference
Section titled “Quick reference”| You want | Write |
|---|---|
| A number | {d} |
| Text | {s} |
| One character from a byte | {c} |
| Hex / binary / octal | {x} {X} / {b} / {o} |
| Scientific notation | {e} |
| Anything, for debugging | {any} |
Your type’s format method |
{f} |
| An optional | {?d}, {?s}, or {any} |
| A string in quotes, escapes visible | {q} |
| An error or enum name | {t} |
| Width 8, left / center / right | {s:<8} {s:^8} {s:>8} |
| Zero padding to 5 digits | {d:0>5} |
| 2 decimal places | {d:.2} |
| Literal braces | {{ and }} |
The full list, with some rarer ones ({B} for byte sizes like 1.5kB, {b64} for base64, {*} for addresses, {qf} for a format method’s output in quotes), is in the doc comment of print in the standard library file lib/std/Io/Writer.zig. The reference’s case study of print shows how Zig checks format strings at compile time.
Practice
Section titled “Practice”1. A neat receipt
Section titled “1. A neat receipt”Print this receipt, with the item names left-aligned in 10 characters, the quantity right-aligned in 5 and the price right-aligned in 8 with 2 decimals:
Item | Qty| Price-------------------------Coffee | 2| 3.50Bagel | 1| 2.25Hint: {s:<10}, {d:>5} and {d:>8.2}. For the line, pad an empty string with -.
Show solution
const std = @import("std");
pub fn main() void { std.debug.print("{s:<10}|{s:>5}|{s:>8}\n", .{ "Item", "Qty", "Price" }); std.debug.print("{s:-<25}\n", .{""}); std.debug.print("{s:<10}|{d:>5}|{d:>8.2}\n", .{ "Coffee", 2, 3.5 }); std.debug.print("{s:<10}|{d:>5}|{d:>8.2}\n", .{ "Bagel", 1, 2.25 });}Output:
Item | Qty| Price-------------------------Coffee | 2| 3.50Bagel | 1| 2.25The same widths on every line make the columns line up. The header uses {s:>5} and {s:>8} so its titles sit over the right-aligned numbers.
2. Colors as hex strings
Section titled “2. Colors as hex strings”Use std.mem.print to turn the color red 200, green 30, blue 5 into the string #c81e05, then print it.
Hint: each part needs exactly two hex digits, so use {x:0>2}. A 7-byte buffer is enough.
Show solution
const std = @import("std");
pub fn main() !void { var buffer: [7]u8 = undefined; const hex = try std.mem.print(&buffer, "#{x:0>2}{x:0>2}{x:0>2}", .{ 200, 30, 5 }); std.debug.print("{s} is {d} bytes long\n", .{ hex, hex.len });}Output:
#c81e05 is 7 bytes longstd.mem.print can fail (if the buffer were too small), so main returns !void and the call uses try. The zero padding turns 5 into 05.
3. A format method for money
Section titled “3. A format method for money”Make a struct Money with a field cents: u32 and a format method, so that printing Money{ .cents = 1999 } with {f} shows $19.99.
Hint: dollars are self.cents / 100 and the rest is self.cents % 100. Pad the cents with {d:0>2}.
Show solution
const std = @import("std");
const Money = struct { cents: u32,
pub fn format(self: Money, writer: *std.Io.Writer) std.Io.Writer.Error!void { try writer.print("${d}.{d:0>2}", .{ self.cents / 100, self.cents % 100 }); }};
pub fn main() void { const price = Money{ .cents = 1999 }; const tip = Money{ .cents = 305 }; std.debug.print("price {f}, tip {f}\n", .{ price, tip });}Output:
price $19.99, tip $3.05{d:0>2} keeps the 05 in $3.05. Without it, you’d get $3.5, which is the wrong amount.
- A print call takes a format string and a tuple
.{ ... }. Zig checks them against each other at compile time. {d}numbers,{s}text,{c}characters,{x}{b}{o}other bases,{e}scientific,{any}anything.- After a
:come fill, alignment, width and precision:{d:0>5},{s:<10},{d:8.2}. Everything is right-aligned by default, text too. - Use
{?d}/{?s}for optionals,{t}for error and enum names, and{{ }}for literal braces. {f}calls your type’sformatmethod. Plain{}silently skips it.{q}shows a string in quotes with escapes, handy when debugging.std.mem.printformats into your own buffer,allocator.printallocates (thenfreeit). The old namesstd.fmt.bufPrintandstd.fmt.allocPrintare deprecated.
Next up: Zig Variables, const, var, undefined and the rules for naming and changing values.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Case study: print in Zig: the official reference on how format strings are checked at compile time.
- Standard library docs (0.17.1): look up
std.fmtandstd.Io.Writer.printfor every function and specifier. - Formatted printing in the 0.17.0 release notes:
{q}and{qf}, plusallocPrintmoving toAllocator.print. - Zig 0.16.0 release notes: formatting changes in 0.16, such as the
{D}duration specifier moving to a format method. {f}required to call format methods (0.15.1 release notes): why{f}exists and how theformatmethod signature changed.