INPUT:
// a slice of type string.
data := []string{"one", "two", "three"}
预期输出:
["one","two","three"]
我尝试过使用这些格式说明符https://play.golang.org/p/zBcFAh7YoVn
fmt.Printf("%+q\n", data)
fmt.Printf("%#q\n", data)
fmt.Printf("%q\n", data)
// using strings.Join()
result := strings.Join(data, ",")
fmt.Println(result)
输出:所有值都没有逗号,
["one" "two" "three"]
[`one` `two` `three`]
["one" "two" "three"]
one,two,three
strings.Builder
,您可以更好地控制输出: data := []string{"one", "two", "three"}
// Expected Output: ["one","two","three"]
var sb strings.Builder
dlim := `"`
sb.WriteString(`[`)
for _, s := range data {
sb.WriteString(dlim)
dlim = `,"`
sb.WriteString(s)
sb.WriteString(`"`)
}
sb.WriteString(`]`)
fmt.Println(sb.String())
strings.Replace(fmt.Sprintf("%q", data), `" "`, `","`, -1)
尝试以下代码:
package main
import (
"fmt"
"strings"
)
func main() {
data := []string{"one", "two", "three"}
// Expected Output: ["one","two","three"]
st := strings.Replace(fmt.Sprintf("%q", data), `" "`, `","`, -1)
fmt.Println(st)
}
输出:
["one","two","three"]