【问题标题】:Replace all variables in Sprintf with same variable用相同的变量替换 Sprintf 中的所有变量
【发布时间】:2021-07-15 05:37:03
【问题描述】:

是否可以使用fmt.Sprintf() 将格式化字符串中的所有变量替换为相同的值?

类似:

val := "foo"
s := fmt.Sprintf("%v in %v is %v", val)

会返回

"foo in foo is foo"

【问题讨论】:

    标签: string go format printf


    【解决方案1】:

    可以,但是必须修改格式字符串,必须使用explicit argument indicies:

    显式参数索引:

    在 Printf、Sprintf 和 Fprintf 中,每个格式化动词的默认行为是格式化调用中传递的连续参数。但是,动词前的符号 [n] 表示要对第 n 个单索引参数进行格式化。宽度或精度的“*”之前的相同符号选择保存该值的参数索引。处理完括号表达式 [n] 后,后续动词将使用参数 n+1、n+2 等,除非另有说明。

    你的例子:

    val := "foo"
    s := fmt.Sprintf("%[1]v in %[1]v is %[1]v", val)
    fmt.Println(s)
    

    输出(在Go Playground上试试):

    foo in foo is foo
    

    当然上面的例子可以简单的写成一行:

    fmt.Printf("%[1]v in %[1]v is %[1]v", "foo")
    

    作为一个小的简化,第一个显式参数索引可以省略,因为它默认为1

    fmt.Printf("%v in %[1]v is %[1]v", "foo")
    

    【讨论】:

      【解决方案2】:

      你也可以使用text/template:

      package main
      
      import (
         "strings"
         "text/template"
      )
      
      func format(s string, v interface{}) string {
         t, b := new(template.Template), new(strings.Builder)
         template.Must(t.Parse(s)).Execute(b, v)
         return b.String()
      }
      
      func main() {
         val := "foo"
         s := format("{{.}} in {{.}} is {{.}}", val)
         println(s)
      }
      

      https://pkg.go.dev/text/template

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-13
        • 2022-01-04
        • 2013-06-28
        相关资源
        最近更新 更多