Go fmt.Printf String Formatting
Go can use fmt.Printf to format strings, as follows:
fmt.Printf(format string, args ...interface{})
Format String: A string containing format specifiers starting with
%
, such as%s
for string and%d
for decimal integer.Argument List: Multiple arguments separated by commas, must correspond in number to the format specifiers, otherwise an error will occur at runtime.
Example
package main
import (
"fmt"
"strings"
)
func main() {
name := "John Doe"
age := 27
// Print string in lowercase
fmt.Printf("hello, %s\n", name)
// Print string in uppercase
fmt.Printf("hello, %s\n", strings.ToUpper(name))
// Print age as a decimal number
fmt.Printf("%s is %d years old\n", name, age)
// Print age as a floating-point number with two decimal places
fmt.Printf("%s is %.2f years old\n", name, age)
}
Output:
hello, John Doe
hello, JOHN DOE
John Doe is 27 years old
John Doe is %!f(int=27) years old
Go String Format Specifiers:
Format | Description |
---|---|
%v | Default format |
%+v | Includes field names for structs |
%#v | Go syntax representation |
%T | Type of the value |
%% | Literal percent sign |
%b | Binary representation |
%o | Octal representation |
%d | Decimal representation |
%x | Hexadecimal representation |
%X | Hexadecimal representation (uppercase) |
%U | Unicode format |
%f | Floating-point number |
%p | Pointer in hexadecimal |
Example
package main
import (
"fmt"
"os"
)
type point struct {
x, y int
}
func main() {
p := point{1, 2}
fmt.Printf("%v\n", p)
fmt.Printf("%+v\n", p)
fmt.Printf("%#v\n", p)
fmt.Printf("%T\n", p)
fmt.Printf("%t\n", true)
fmt.Printf("%d\n", 123)
fmt.Printf("%b\n", 14)
fmt.Printf("%c\n", 33)
fmt.Printf("%x\n", 456)
fmt.Printf("%f\n", 78.9)
fmt.Printf("%e\n", 123400000.0)
fmt.Printf("%E\n", 123400000.0)
fmt.Printf("%s\n", "\"string\"")
fmt.Printf("%q\n", "\"string\"")
fmt.Printf("%x\n", "hex this")
fmt.Printf("%p\n", &p)
fmt.Printf("|%6d|%6d|\n", 12, 345)
fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)
fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)
fmt.Printf("|%6s|%6s|\n", "foo", "b")
fmt.Printf("|%-6s|%-6s|\n", "foo", "b")
s := fmt.Sprintf("a %s", "string")
fmt.Println(s)
fmt.Fprintf(os.Stderr, "an %s\n", "error")
}
Output:
{1 2}
{x:1 y:2}
main.point{x:1, y:2}
main.point
true
123
1110
!
1c8
78.900000
1.234000e+08
1.234000E+08
"string"
"\"string\""
6865782074686973
0xc0000b4010 | 12| 345| | 1.20| 3.45| |1.20 |3.45 | | foo| b| |foo |b | a string an error ```