Golang String Padding Example
String padding in Go (Golang) is referred as the operation to prepending or appending spaces or characters to a string such that the total lenght of the final string is fixed, regardless of the input string’s length. You may have encountered a scenario where you had to display or format data in such way, such that it is aligned like in a table. Let’s see an example
athletes distances john 10km marylin 131km joe 0.5km arthur 1km
athletes are aligned to the left, distances are aligned to the right. In Go (Golang) padding can be done using just the standard library without having to write the padding logic by yourself or having to import third party libraries.
Use the fmt package for padding and formatting
In Go (Golang) you can use the fmt package to add padding to your strings. You can use the
width option as defined in the fmt package.
Width is specified by an optional decimal number immediately preceding the verb. If absent
%f default width, default precision
%9f width 9, default precision
%.2f default width, precision 2
%9.2f width 9, precision 2
%9.f width 9, precision 0
Let’s see some examples how
Padding with zeroes
Padding with arbitrary length
You can also define the padding width using a asterisk and specifying a parameter representing the length of the padding.
fmt.Println("'%*dkm'", 10, 2)
More Formatting Directives
You can check more formatting directives that can be applied when using the fmt package in the official documentation page
+ always print a sign for numeric values; guarantee ASCII-only output for %q (%+q) - pad with spaces on the right rather than the left (left-justify the field) # alternate format: add leading 0b for binary (%#b), 0 for octal (%#o), 0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p); for %q, print a raw (backquoted) string if strconv.CanBackquote returns true; always print a decimal point for %e, %E, %f, %F, %g and %G; do not remove trailing zeros for %g and %G; write e.g. U+0078 'x' if the character is printable for %U (%#U). ' ' (space) leave a space for elided sign in numbers (% d); put spaces between bytes printing strings or slices in hex (% x, % X) 0 pad with leading zeros rather than spaces; for numbers, this moves the padding after the sign ```