In Go, you can pad strings and numbers with leading zeros in formatted output using the fmt
package. The Printf
function allows you to specify the width and padding character in the format string.
Here's an example that demonstrates how to pad strings and numbers with leading zeros:
package main
import "fmt"
func main() {
str := "hello"
num := 42
// Pad string with leading zeros to a width of 8
fmt.Printf("%08s\n", str) // Output: 000hello
// Pad number with leading zeros to a width of 6
fmt.Printf("%06d\n", num) // Output: 000042
}
In the format string, %0X
is used to specify zero padding, where X
represents the width. In the above example, %08s
pads the string with leading zeros to a width of 8 characters, and %06d
pads the number with leading zeros to a width of 6 digits.
You can change the width and padding character as per your requirements.