用相同的变量替换Sprintf中的所有变量 [英] Replace all variables in Sprintf with same variable

查看:447
本文介绍了用相同的变量替换Sprintf中的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



类似于:

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

会返回

 foo in foo is foo


解决方案

这是可能的,但格式字符串必须修改,您必须使用 显式参数指示
$ b


显式参数索引:

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


您的示例:

  val:=foo
s:= fmt.Sprintf(%[1] v在%[1] v是%[1] v,val)
fmt.Println(s)

输出(在 Go Playground 上试用):

  foo在foo中是foo 



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

$ $ $ $ $ $ $ $ $ $ $ %[1] v是%[1] v,foo)

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

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


Is it possible using fmt.Sprintf() to replace all variables in the formatted string with the same value?

Something like:

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

which would return

"foo in foo is foo"

解决方案

It's possible, but the format string must be modified, you must use explicit argument indicies:

Explicit argument indexes:

In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.

Your example:

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

Output (try it on the Go Playground):

foo in foo is foo

Of course the above example can simply be written in one line:

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

Also as a minor simplification, the first explicit argument index may be omitted as it defaults to 1:

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

这篇关于用相同的变量替换Sprintf中的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆