Printf
Often in Go we want to output columns of data from our important computations. With the fmt.Printf
method, we can specify a couple characters to apply padding.
With a minus sign, we add spaces to the right. With a positive number (no minus sign) we add spaces to the left, which pushes the text to the right.
An example of right-align and left-align is more helpful. Here we create columns of 10 characters wide. If a string
is not long enough, it is padded with spaces.
package main import "fmt" func main() { values := []string{"bird", "5", "animal"} // Pad all values to 10 characters. // ... This right-justifies the strings. // Three periods just for decoration. for i := range(values) { fmt.Printf("%10v...\n", values[i]) } // Pad all values to 10 characters. // ... This left-justifies the strings. // Vertical bars just for decoration. for i := range(values) { fmt.Printf("|%-10v|\n", values[i]) } } bird... 5... animal... |bird | |5 | |animal |
Sometimes we want to get a string
with padding—not directly print it to the console. Here fmt.Sprintf
is useful. It returns a padded string
.
package main import "fmt" func main() { input := "pad" // Pad the string and store it in a new string. padded := fmt.Sprintf("%12v", input) fmt.Println("Len:", len(padded)) fmt.Println("[" + padded + "]") }Len: 12 [ pad]
We use a positive or negative number in front of the format code (like "%v"). The "v" stands for "value" and can handle many types.
Padding can make an unreadable list of values readable. With Printf
we can write multiple strings onto the same line, creating columnar layouts.