⇠ back to TILs

Go's package fmt %q verb for strings

I wasn't aware of the Go fmt package %q verb, for quoting strings. Typically, I've been escaping the quotes manually and using the %s verb: fmt.Sprintf("this needs quoting: \"%s\"", "input"). But the %q verb obviates the need for that manual quoting.

From the package documentation:

%s the uninterpreted bytes of the string or slice

%q a double-quoted string safely escaped with Go syntax

And a quick example (on the Go Playground):

package main

import (

func main() {
	test := "I'm a test string"
	fmt.Printf("\"%s\"", test)
	// Output: "I'm a test string"
	fmt.Printf("%q", test)
	// Output: "I'm a test string"

Thoughts? Corrections? Feel free to reply via email!