fmt.Printf
- Go course
- Intermediate
- Lesson 53/80
- 4 min
Learn Printf and format verbs.
fmt.Printf
fmt.Printf takes a format string and values; the verbs in the string (placeholders starting with %) are filled with the values in order. Unlike Println it doesn't add a newline by itself.
ad, yas := "Ada", 36
fmt.Printf("%s %d yaşında\n", ad, yas)
// Ada 36 yaşındaIf a verb doesn't match the value's type the program doesn't crash; a warning like %!d(string=Ada) is written to the output. go vet catches these mistakes before compiling.
Width and precision
Width and precision can be added before the verb: %8.2f means a number at least 8 characters wide with 2 decimals. - left-aligns and 0 pads with zeros:
fmt.Printf("|%6d|%-6d|%06d|\n", 42, 42, 42)
// | 42|42 |000042|
fmt.Printf("%.2f\n", 3.14159) // 3.14These fields are very handy for tabular output.
Practice Price table
Print two products aligned with Printf: name left-aligned in 8 characters (%-8s), price 7 characters wide with 2 decimals (%7.2f). Products: Kalem 12.5, Defter 7.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
fmt.Printf("%-8s%7.2f\n", "Kalem", 12.5)
fmt.Printf("%-8s%7.2f\n", "Defter", 7.0)
}Expected output
Kalem 12.50 Defter 7.00
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>fmt.Printf("%d\n", "on")</code> print?
- 10
- on
- The program crashes
- %!d(string=on) Correct answer
Explanation: fmt marks the wrong verb in the output; there's no run-time panic. go vet warns about this line.
2 Two decimals
fmt.Printf("____
", 9.876) // 9.88
fmt.Printf("%.2f
", 9.876) // 9.88
Explanation: %.2f rounds the number to 2 digits after the decimal point.
3 Format and output (42)
| Term | Meaning |
|---|---|
%d |
42 |
%5d |
" 42" |
%-5d| |
"42 |" |
%05d |
00042 |