Format Strings
format(fmt, ...) returns a formatted string. printf(fmt, ...) prints it with a trailing newline. Both use the C++ {fmt} library through fmt::vformat, so the syntax is close to Python’s str.format with C-style format specifiers.
printf("Hello {}!", "world") # Hello world!printf("{:.2f}", 3.14159) # 3.14
let s = format("{} + {} = {}", 1, 2, 3)printf("{{{}}}", 42) # {42}printf("{1} {0}", "a", "b") # b aArguments
Section titled “Arguments”{} consumes the next argument. {0} and {1} address arguments by index, and indices can repeat or be reordered.
printf("{} {} {}", "a", "b", "c") # a b cprintf("{2} {0}", "a", "b", "c") # c aprintf("{0} {0}", "again") # again againExtra arguments are ignored.
printf("{}", 1, 2) # 1The first argument must be a string. A malformed format raises ArgumentError with a Format error: ... message.
Escaping
Section titled “Escaping”{{ renders a literal {, and }} renders a literal }.
printf("{{}}", 1) # {}printf("{{{}}}", 42) # {42}Format specs
Section titled “Format specs”Format specs appear after :. They are type-strict.
| Type | Specs | Example |
|---|---|---|
| Float | f, e, g, precision, width |
{:.2f}, {:e}, {:>8.2f} |
| Int | d, x, X, o, b, c |
{:d}, {:05d}, {:#x} |
| String | s |
{:s} |
| Alignment | <, >, ^ with width |
{:>10}, {:^10} |
printf("{:.2f}", 3.14159) # 3.14printf("{:.0f}", 3.6) # 4printf("{:g}", 3.14159) # 3.14159printf("{:e}", 1234.5) # 1.234500e+03
printf("{:d}", 42) # 42printf("{:05d}", 42) # 00042printf("{:08d}", 42) # 00000042printf("{:x}", 255) # ffprintf("{:#x}", 255) # 0xffprintf("{:b}", 5) # 101printf("{:c}", 65) # A
printf("{:>10}", "right") # rightprintf("{:<10}", "left") # leftprintf("{:^10}", "center") # centerprintf("{:>8.2f}", 3.14159) # 3.14printf("{:+d}", 42) # +42printf("{: }", 42) # 42Passing a float to an integer spec or an int to a float spec raises ArgumentError.
format("{:.2f}", 5) # ArgumentErrorformat("{:d}", 5.0) # ArgumentErrorNot supported
Section titled “Not supported”- Named fields such as
{name}raiseArgumentError: Format error: argument not found. - The
,grouping option ({,d},{,.2f}) raisesinvalidformatspecifier.
Argument conversion
Section titled “Argument conversion”Ints, floats, and bools use their natural presentation. none becomes none. Any other value uses its display string, so arrays print like [1, 2].
printf("{}", [1, 2, 3]) # [1, 2, 3]printf("{}", none) # noneprintf("{}", true) # true