Padding, 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.
Example program. 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 |
Sprintf, padding. 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]
Notes, padding. 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.
Tip Padding works with other format codes like "%d" for numeric codes. Other flags may also be applied in the same format.
A review. Padding can make an unreadable list of values readable. With Printf we can write multiple strings onto the same line, creating columnar layouts.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 7, 2021 (image).