【问题标题】:How to print Slice with comma seperated values in golang如何在golang中使用逗号分隔值打印切片
【发布时间】:2020-08-13 08:35:12
【问题描述】:

输入:

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

【问题讨论】:

  • 不能用 fmt.Sprintf 做到这一点,无论你使用什么动词和修饰语。如果要生成 JSON:使用 encoding/json.Marshal。如果不需要引用:通过[" + strings.Join(data, ",") + "] 自己构造字符串。如果需要引用:写一个循环。

标签: string go format slice


【解决方案1】:
// define slice
args := []string{"one", "two", "three"}

// prepend single quote, perform joins, append single quote
output := "'"+strings.Join(args, `','`) + `'`

fmt.Println(output)

去游乐场:https://play.golang.org/p/pKu0sO_QsGo

【讨论】:

  • 这不能正确处理带引号的字符串,例如[]string{"o\"ne", "two", "three"}
【解决方案2】:

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

如果字符串包含双引号,则仅使用 Join 会创建损坏的值。

【讨论】:

    【解决方案3】:

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

    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

    【讨论】:

      【解决方案4】:
      data := []string{"1",  "2"}
      
      var result string 
      if len(data) > 0 {
          result = "\"" + strings.Join(data, "\",\"") + "\""
      }
      fmt.Println(result)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-10
        • 2017-12-19
        • 2014-08-07
        • 2019-09-09
        • 2011-11-23
        • 1970-01-01
        • 1970-01-01
        • 2019-02-22
        相关资源
        最近更新 更多