DEV Community

Michele Caci
Michele Caci

Posted on

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

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
}
Enter fullscreen mode Exit fullscreen mode

For a more in-depth overview head to the fmt package reference.

Top comments (0)