CodeBlanks Logo Icon CodeBlanks

fmt.Sprintf

Learn to return a formatted string with Sprintf.

fmt.Sprintf

Sprintf does the same formatting as Printf but returns the result as a string instead of writing it to the screen. It is used to build messages, keys and file names:

dosya := fmt.Sprintf("rapor-%04d-%02d.csv", 2026, 3)
// rapor-2026-03.csv

The three family members: Print (stdout), Fprint (a given Writer), Sprint (a string). Each has …f and …ln variants.

Sprint vs Sprintln

Sprint adds a space between two non-string values but not between strings; Sprintln adds a space between every value and a newline at the end:

fmt.Sprint("a", "b", 1, 2)    // "ab1 2"
fmt.Sprintln("a", "b", 1, 2)  // "a b 1 2\n"

For readable, predictable output Sprintf is usually preferred.

Practice Build a file name

Write dosyaAdi(yil, ay int, tur string) string; it builds a name like "rapor-2026-03.csv" (month in two digits). Print dosyaAdi(2026, 3, "csv").

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func dosyaAdi(yil, ay int, tur string) string {
    return fmt.Sprintf("rapor-%d-%02d.%s", yil, ay, tur)
}

func main() {
    fmt.Println(dosyaAdi(2026, 3, "csv"))
}

Expected output

rapor-2026-03.csv

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In a hot loop, which is faster for converting a single number to a string?

  • string(n)
  • strconv.Itoa(n) Correct answer
  • fmt.Sprintf("%d", n)
  • fmt.Sprint(n)

Explanation: Sprintf parses the format string and boxes the value into an interface; strconv converts directly. string(n) turns the number into a rune, not digits.

2 Build text

Question
anahtar := fmt.____("kullanici:%d", id)
Answer
anahtar := fmt.Sprintf("kullanici:%d", id)

Explanation: Sprintf returns the formatted text as a string.

3 Function and target

Term Meaning
Printf Standard output
Fprintf A given io.Writer
Sprintf A returned string
Errorf A returned error

All lessons in Intermediate