Skip to main content

Go Formatting Verbs

Printf() decides how to display each value by reading small placeholders called formatting verbs. Go has a good number of them, and the sections below group them by the kind of data they work with.


General Formatting Verbs

A few verbs are not tied to one kind of data. These work with a value of any type:

  • %v - shows the value in Go's default style
  • %#v - shows the value as you would write it in Go source code
  • %T - shows the value's type rather than the value itself
  • %% - shows a literal percent sign

Example

Prompt
Use %v, %#v, %T, and %% formatting verbs with Printf on different types.
Output: Go program and captured output

Integer Formatting Verbs

Whole numbers have the richest set of options. You can choose the number base, show the sign, or control how wide the result is:

  • %b - binary (base 2)
  • %d - decimal (base 10)
  • %+d - decimal, always showing the sign
  • %o - octal (base 8)
  • %O - octal, starting with 0o
  • %x - hexadecimal (base 16) in lowercase letters
  • %X - hexadecimal (base 16) in capital letters
  • %#x - hexadecimal, starting with 0x
  • %4d - at least 4 characters wide, filled with spaces on the left
  • %-4d - at least 4 characters wide, filled with spaces on the right
  • %04d - at least 4 characters wide, filled with leading zeros

Example

Prompt
Use integer formatting verbs %b, %d, %+d, %o, %O, %x, %X, and %#x with Printf.
Output: Go program and captured output

String Formatting Verbs

Text has its own verbs, including ones that add quotes or reserve a set amount of space:

  • %s - the text exactly as it is
  • %q - the text wrapped in double quotes
  • %8s - the text aligned to the right in a field 8 characters wide
  • %-8s - the text aligned to the left in a field 8 characters wide
  • %x - a hexadecimal dump of the text's bytes

Example

Prompt
Use string formatting verbs %s, %q, %8s, %-8s, and %x with Printf.
Output: Go program and captured output

Boolean Formatting Verbs

Booleans need just one verb:

  • %t - displays either true or false

Example

Prompt
Use the %t formatting verb to print a boolean value.
Output: Go program and captured output

Float Formatting Verbs

For numbers with a fractional part, these verbs set the notation, the width and the number of decimal places:

  • %e - scientific notation using an e
  • %f - plain decimal notation with no exponent
  • %.2f - two digits after the point, with no set width
  • %6.2f - a field 6 characters wide with two digits after the point
  • %g - adds an exponent only when needed and drops needless digits

Example

Prompt
Use float formatting verbs %e, %f, %.2f, %6.2f, and %g with Printf.
Output: Go program and captured output