HomeSearch

Golang Padding String Example (Right or Left Align)

Use padding on strings to right-align or left-align text into columns.
Padding, Printf. Often 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.
Golang program that uses padding with fmt.Printf 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]) } } Output 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.
Golang program that uses padding with fmt.Sprintf 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 + "]") } Output 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.fmt
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls