英文:
How to interpolate a number inside a string
问题
以下是翻译好的内容:
以下代码
package main
import (
"fmt"
)
func main() {
fmt.Println(say(9))
}
func say(num int)(total string){
return fmt.Sprintf("There are %s reasons to code!", num)
}
产生以下输出
There are %!s(int=9) reasons to code!
我的问题
我应该如何在字符串中插入一个数字?
英文:
The following code
package main
import (
"fmt"
)
func main() {
fmt.Println(say(9))
}
func say(num int)(total string){
return fmt.Sprintf("There are %s reasons to code!", num)
}
Produces the following output
There are %!s(int=9) reasons to code!
My question
What should I do to interpolate a number inside a string?
答案1
得分: 46
如果你想始终使用“默认”表示,无论是什么类型,可以使用%v
,例如:
fmt.Sprintf("There are %v reasons to code!", num)
英文:
If you want to always use the "default" representation of no matter what type, use %v
as in
fmt.Sprintf("There are %v reasons to code!", num)
答案2
得分: 16
请尝试使用%d
代替%s
。其中,d
代表十进制。
相关的文档可以在这里找到:
英文:
Try %d
instead of %s
. The d stands for decimal.
The appropriate documentation is here:
答案3
得分: 3
输出正好说明了正在发生的事情和你需要知道的内容!
由于你试图使用一个名为**%s的动词**,输出显示:
!s(int=0)
这意味着:
这个值不是一个字符串,而是一个整数。
因此,如果你想知道应该使用什么替代方案,请查看 fmt 包页面 https://golang.org/pkg/fmt/ 上的 "integers" 表格:
%b 二进制
%c 对应的 Unicode 代码点表示的字符
%d 十进制
%o 八进制
%q 使用 Go 语法安全转义的单引号字符文字
%x 十六进制,小写字母为 a-f
%X 十六进制,大写字母为 A-F
%U Unicode 格式:U+1234;与 "U+%04X" 相同
因此,你可以使用这些动词中的任何一个来正确表示输出。
或者如之前的回答所说,你也可以使用 %v 动词,它表示:
"以其默认格式显示值"。
英文:
The output is saying exactly what is happening and what you need to know!
As you are trying to use a %s verb which is meant to strings the output says that:
!s(int=0)
which means:
> The value is not a string, but an integer.
Thus, if you want to know what to use instead take a look at the fmt package page https://golang.org/pkg/fmt/ at the "integers" table:
%b base 2
%c the character represented by the corresponding Unicode code point
%d base 10
%o base 8
%q a single-quoted character literal safely escaped with Go syntax.
%x base 16, with lower-case letters for a-f
%X base 16, with upper-case letters for A-F
%U Unicode format: U+1234; same as "U+%04X"
So you can use any of this verbs to have the output correctly represented.
Or as previous answers says, you can also use the %v verb which means:
"the value in its default format".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论