如果我想执行以下操作:
a := "%shello%s"
b:= fmt.Sprintf("%sWorld",a)
fmt.Printf(b)
Run Code Online (Sandbox Code Playgroud)
我要列印
%shello%sWorld
Run Code Online (Sandbox Code Playgroud)
即%s仅在%sWorld中被替换。
我怎样才能做到这一点?
我不想用替换 %%shello%%s
a := "%shello%s"
b:= fmt.Sprintf("%sWorld",a)
Run Code Online (Sandbox Code Playgroud)
这工作得很好,它导致字符串是"%shello%sWorld"。
问题在于您如何打印它:
fmt.Printf(b)
Run Code Online (Sandbox Code Playgroud)
fmt.Printf()视为b格式字符串,并且由于b的值包含%s,因此希望您也传递参数(您没有),因此实际输出包含错误消息。
而是使用fmt.Println():
fmt.Println(b)
Run Code Online (Sandbox Code Playgroud)
输出将是(在Go Playground上尝试):
%shello%sWorld
Run Code Online (Sandbox Code Playgroud)