如何在Go语言中格式化字符串时索引参数[duplicate]

ep6jt1vc  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(104)

此问题在此处已有答案

Is there a way to reuse an argument in fmt.Printf?(2个答案)
Refer to the same parameter multiple times in a fmt.Sprintf format string [duplicate](2个答案)
上个月关门了。
假设我有一个字符串"Hello %s. How are you %s",我想把同一个字符串放在两个%s中用途:

fmt.Printf("Hello %s. How are you %s", "KK", "KK") // returns "Hello KK. How are you KK"

是否有方法对参数进行索引,这样我就不必重复"KK"

z9smfwbn

z9smfwbn1#

找到了一种方法。语法如下:

fmt.Printf("Hello %[1]s. How are you %[1]s", "KK") // returns "Hello KK. How are you KK"

其中%[1]s表示要格式化的字符串后面的第一个参数。您也可以执行类似以下操作:

fmt.Printf("Hello %[1]s. How are you %[1]s. Where are you %[2]s", "KK", "today") // returns "Hello KK. How are you KK. Where are you today"

相关问题