如何在golang中使用逗号分隔值打印切片

输入:


    // 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


Qyouu
浏览 734回答 3
3回答

白衣非少年

// define sliceargs := []string{"one", "two", "three"}// prepend single quote, perform joins, append single quoteoutput := "'"+strings.Join(args, `','`) + `'`fmt.Println(output)去游乐场: https: //play.golang.org/p/pKu0sO_QsGo

jeck猫

JSON 生成一个很好的转义 csvhttps://go.dev/play/p/Qgh2WgOvAUWdata := []string{"1", "2", "A", "B", "Hack\"er"}b, _ := json.Marshal(data)fmt.Printf("%v", string(b)) // ["1", "2", "A", "B", "Hack\"er"]Join如果字符串包含双引号,则仅使用会创建损坏的值。

白板的微信

data := []string{"1",  "2"}var result string if len(data) > 0 {    result = "\"" + strings.Join(data, "\",\"") + "\""}fmt.Println(result)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go