Padding, Printf. Often in Golang 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 7, 2021 (image).