Moh*_*til 9 string format go slice
输入:
// a slice of type string.
data := []string{"one", "two", "three"}
Run Code Online (Sandbox Code Playgroud)
预期输出:
["one","two","three"]
Run Code Online (Sandbox Code Playgroud)
我尝试使用这些格式说明符 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)
Run Code Online (Sandbox Code Playgroud)
输出: 所有值都没有逗号,
["one" "two" "three"]
[`one` `two` `three`]
["one" "two" "three"]
one,two,three
Run Code Online (Sandbox Code Playgroud)
JSON 生成一个漂亮的转义 csv
https://go.dev/play/p/Qgh2WgOvAUW
data := []string{"1", "2", "A", "B", "Hack\"er"}
b, _ := json.Marshal(data)
fmt.Printf("%v", string(b)) // ["1", "2", "A", "B", "Hack\"er"]
Run Code Online (Sandbox Code Playgroud)
Join如果字符串包含双引号,则仅使用就会创建损坏的值。
// define slice
args := []string{"one", "two", "three"}
// prepend single quote, perform joins, append single quote
output := "'"+strings.Join(args, `','`) + `'`
fmt.Println(output)
Run Code Online (Sandbox Code Playgroud)
去游乐场:https://play.golang.org/p/pKu0sO_QsGo
不知道这会有帮助,但也只是添加我的想法!
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出
[ 'one', 'two', 'three' ]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19261 次 |
| 最近记录: |