DEV Community

loading...

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

mcaci profile image Michele Caci ・1 min read

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.

Discussion (0)

pic
Editor guide