ZetCode

Golang fmt.Sprintf function

last modified May 8, 2025

This tutorial explains how to use the fmt.Sprintf function in Go. We'll cover string formatting basics with practical examples of common use cases.

The fmt.Sprintf function formats strings in Go without printing them. It returns a formatted string rather than writing to standard output. This is useful for creating strings with dynamic content.

In Go, fmt.Sprintf uses format verbs similar to C's printf. It supports various data types and formatting options. The function is part of Go's fmt package, which handles I/O formatting.

Basic string formatting

The simplest use of fmt.Sprintf combines static text with variables. This example demonstrates basic string formatting with different data types.
Note: Format verbs like %s and %d specify how to format values.

basic_format.go
package main

import (
    "fmt"
)

func main() {
    name := "Alice"
    age := 28
    height := 1.72
    
    result := fmt.Sprintf("%s is %d years old and %.2f meters tall", 
        name, age, height)
    
    fmt.Println(result)
}

The format string contains verbs replaced by variable values. %s formats strings, %d formats integers, and %.2f formats floats with 2 decimal places.

Integer formatting options

fmt.Sprintf provides various options for formatting integers. This example shows different base representations and padding options.

integer_format.go
package main

import "fmt"

func main() {
    num := 42
    
    dec := fmt.Sprintf("Decimal: %d", num)
    hex := fmt.Sprintf("Hexadecimal: %x", num)
    oct := fmt.Sprintf("Octal: %o", num)
    bin := fmt.Sprintf("Binary: %b", num)
    pad := fmt.Sprintf("Padded: %04d", num)
    
    fmt.Println(dec)
    fmt.Println(hex)
    fmt.Println(oct)
    fmt.Println(bin)
    fmt.Println(pad)
}

Different format verbs display numbers in various bases. %04d pads the number with zeros to ensure 4-digit width. This is useful for consistent formatting.

Floating-point precision

Floating-point numbers can be formatted with specific precision. This example demonstrates controlling decimal places and scientific notation.

float_format.go
package main

import "fmt"

func main() {
    pi := 3.1415926535
    
    defaultFmt := fmt.Sprintf("Default: %f", pi)
    twoDec := fmt.Sprintf("Two decimals: %.2f", pi)
    sciNot := fmt.Sprintf("Scientific: %e", pi)
    largeNum := fmt.Sprintf("Large: %g", 123456789.123456789)
    
    fmt.Println(defaultFmt)
    fmt.Println(twoDec)
    fmt.Println(sciNot)
    fmt.Println(largeNum)
}

%.2f limits output to 2 decimal places. %e uses scientific notation, while %g automatically chooses between decimal and scientific notation based on value.

String and character formatting

fmt.Sprintf provides specialized formatting for strings and characters. This example shows width control, quoting, and Unicode handling.

string_format.go
package main

import "fmt"

func main() {
    str := "hello"
    char := 'δΈ–'
    
    padded := fmt.Sprintf("Padded: %10s", str)
    quoted := fmt.Sprintf("Quoted: %q", str)
    unicode := fmt.Sprintf("Character: %U", char)
    charRep := fmt.Sprintf("Char: %c", char)
    
    fmt.Println(padded)
    fmt.Println(quoted)
    fmt.Println(unicode)
    fmt.Println(charRep)
}

%10s right-pads the string with spaces to 10 characters. %q adds quotes around the string. %U displays Unicode code points, and %c shows the actual character.

Boolean and pointer formatting

fmt.Sprintf can format boolean values and pointers. This example shows how to display truth values and memory addresses.

bool_ptr_format.go
package main

import "fmt"

func main() {
    flag := true
    num := 42
    ptr := &num
    
    boolFmt := fmt.Sprintf("Boolean: %t", flag)
    ptrFmt := fmt.Sprintf("Pointer: %p", ptr)
    typeFmt := fmt.Sprintf("Type: %T", ptr)
    
    fmt.Println(boolFmt)
    fmt.Println(ptrFmt)
    fmt.Println(typeFmt)
}

%t formats boolean values as true/false. %p displays pointer addresses in hexadecimal. %T shows the type of a variable, useful for debugging.

Struct and custom formatting

fmt.Sprintf can format structs and implement custom Stringer interface. This example demonstrates struct formatting options.

struct_format.go
package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func (p Person) String() string {
    return fmt.Sprintf("%s (%d years)", p.Name, p.Age)
}

func main() {
    p := Person{"Bob", 35}
    
    defaultFmt := fmt.Sprintf("Default: %v", p)
    fieldNames := fmt.Sprintf("With fields: %+v", p)
    goSyntax := fmt.Sprintf("Go syntax: %#v", p)
    customFmt := fmt.Sprintf("Custom: %s", p)
    
    fmt.Println(defaultFmt)
    fmt.Println(fieldNames)
    fmt.Println(goSyntax)
    fmt.Println(customFmt)
}

%v shows struct values, %+v includes field names, and %#v displays Go syntax. The String() method enables custom formatting when using %s verb.

Complex formatting with width and precision

fmt.Sprintf supports advanced formatting with width and precision specifiers. This example shows sophisticated formatting combinations.

advanced_format.go
package main

import "fmt"

func main() {
    products := []struct {
        Name  string
        Price float64
    }{
        {"Laptop", 999.99},
        {"Phone", 699.50},
        {"Tablet", 450.00},
    }
    
    var report string
    for _, p := range products {
        line := fmt.Sprintf("| %-10s | %8.2f |\n", p.Name, p.Price)
        report += line
    }
    
    header := fmt.Sprintf("| %-10s | %8s |\n", "Product", "Price")
    separator := fmt.Sprintf("|%-12s|%-10s|\n", "------------", "----------")
    
    fmt.Print(header + separator + report)
}

%-10s left-aligns strings in 10-character width. %8.2f right-aligns floats in 8-character width with 2 decimals. This creates neatly aligned columns.

Source

Go fmt package documentation

This tutorial covered the fmt.Sprintf function in Go with practical examples of string formatting for various data types and scenarios.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Golang tutorials.