gpt4 book ai didi

string - 如何在golang中用逗号分隔值打印Slice

转载 作者:行者123 更新时间:2023-12-01 22:44:22 26 4
gpt4 key购买 nike

输入:

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

最佳答案

不知道这会有所帮助,但也只是增加我的想法!

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' ]

PlayGroundLink

关于string - 如何在golang中用逗号分隔值打印Slice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61498687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com