用相同的变量替换 Sprintf 中的所有变量 [英] Replace all variables in Sprintf with same variable
问题描述
是否可以使用 fmt.Sprintf()
将格式化字符串中的所有变量替换为相同的值?
Is it possible using fmt.Sprintf()
to replace all variables in the formatted string with the same value?
类似:
val := "foo"
s := fmt.Sprintf("%v in %v is %v", val)
会返回
"foo in foo is foo"
推荐答案
可以,但是必须修改格式字符串,必须使用显式参数索引:
It's possible, but the format string must be modified, you must use explicit argument indicies:
显式参数索引:
在 Printf、Sprintf 和 Fprintf 中,每个格式化动词的默认行为是格式化调用中传递的连续参数.但是,动词前的符号 [n] 表示要对第 n 个单索引参数进行格式化.宽度或精度的*"之前的相同符号选择保存该值的参数索引.处理完括号表达式 [n] 后,后续动词将使用参数 n+1、n+2 等,除非另有说明.
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.
你的例子:
val := "foo"
s := fmt.Sprintf("%[1]v in %[1]v is %[1]v", val)
fmt.Println(s)
输出(在 Go Playground 上试试):
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")
作为一个小的简化,第一个显式参数索引可以省略,因为它默认为 1
:
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屋!