String 如何在golang中打印逗号分隔值的切片
输入:String 如何在golang中打印逗号分隔值的切片,string,go,format,slice,String,Go,Format,Slice,输入: // a slice of type string. data := []string{"one", "two", "three"} ["one","two","three"] 预期输出: // a slice of type string. data := []string{"one", "two", "three"} ["one","two","three"] 我尝试使用这些格式说明符 输出: 所有值都没有逗号 ["one" "two" "t
// a slice of type string.
data := []string{"one", "two", "three"}
["one","two","three"]
预期输出:
// a slice of type string.
data := []string{"one", "two", "three"}
["one","two","three"]
我尝试使用这些格式说明符
输出:
所有值都没有逗号
["one" "two" "three"]
[`one` `two` `three`]
["one" "two" "three"]
one,two,three
我不知道这会有什么帮助,但我只是想补充一下我的想法
package main
import "fmt"
func main() {
data := []string{"one", "two", "three"}
//fmt.Println(data)
for index, j := range data {
if index == 0 { //If the value is first one
fmt.Printf("[ '%v', ", j)
} else if len(data) == index+1 { // If the value is the last one
fmt.Printf("'%v' ]", j)
} else {
fmt.Printf(" '%v', ", j) // for all ( middle ) values
}
}
}
输出
[ 'one', 'two', 'three' ]
去操场:无论使用什么动词和修饰语,fmt.Sprintf都不能这样做。如果要生成JSON:请使用encoding/JSON.Marshal。如果不需要引用:通过[“
+strings.Join(数据,”,“
)+”]
自己构造字符串。如果需要引用:写一个循环。
data := []string{"1", "2"}
var result string
if len(data) > 0 {
result = "\"" + strings.Join(data, "\",\"") + "\""
}
fmt.Println(result)