Using '%q' inside fmt.Printf in Go (instead of '%s')

date
Jan 25, 2023
slug
go-fmt-use-q-instead-of-s
status
Published
tags
Go
summary
When printing a string in Go you can use the verb %q in the format parameters of fmt functions, when available, to safely escape a string and add quotes to it.
type
Post
When printing a string in Go you can use the verb %q in the format parameters of fmt functions, when available, to safely escape a string and add quotes to it.
For example:
import "fmt"

func main() {
    fmt.Printf("%s\n", "hello") // prints hello
    fmt.Printf("%q\n", "hello") // prints "hello"
    fmt.Printf("%s\n", "hello\n;") // prints hello
//; \n is not escaped
    fmt.Printf("%q\n", "hello\n;") // prints "hello\n;" \n is escaped here
}
For a more in-depth overview head to the fmt package reference.
 

© therainisme 2025