如何在字符串中插值一个数字

huangapple go评论105阅读模式
英文:

How to interpolate a number inside a string

问题

以下是翻译好的内容:

以下代码

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. fmt.Println(say(9))
  7. }
  8. func say(num int)(total string){
  9. return fmt.Sprintf("There are %s reasons to code!", num)
  10. }

产生以下输出

  1. There are %!s(int=9) reasons to code!

我的问题

我应该如何在字符串中插入一个数字?

英文:

The following code

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. fmt.Println(say(9))
  7. }
  8. func say(num int)(total string){
  9. return fmt.Sprintf("There are %s reasons to code!", num)
  10. }

Produces the following output

  1. There are %!s(int=9) reasons to code!

My question

What should I do to interpolate a number inside a string?

答案1

得分: 46

如果你想始终使用“默认”表示,无论是什么类型,可以使用%v,例如:

  1. 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

  1. fmt.Sprintf("There are %v reasons to code!", num)

答案2

得分: 16

请尝试使用%d代替%s。其中,d代表十进制。

相关的文档可以在这里找到:

http://golang.org/pkg/fmt/

英文:

Try %d instead of %s. The d stands for decimal.

The appropriate documentation is here:

http://golang.org/pkg/fmt/

答案3

得分: 3

输出正好说明了正在发生的事情和你需要知道的内容!
由于你试图使用一个名为**%s动词**,输出显示:
!s(int=0) 这意味着:

这个值不是一个字符串,而是一个整数。

因此,如果你想知道应该使用什么替代方案,请查看 fmt 包页面 https://golang.org/pkg/fmt/ 上的 "integers" 表格:

  1. %b 二进制
  2. %c 对应的 Unicode 代码点表示的字符
  3. %d 十进制
  4. %o 八进制
  5. %q 使用 Go 语法安全转义的单引号字符文字
  6. %x 十六进制,小写字母为 a-f
  7. %X 十六进制,大写字母为 A-F
  8. %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:

  1. %b base 2
  2. %c the character represented by the corresponding Unicode code point
  3. %d base 10
  4. %o base 8
  5. %q a single-quoted character literal safely escaped with Go syntax.
  6. %x base 16, with lower-case letters for a-f
  7. %X base 16, with upper-case letters for A-F
  8. %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".

huangapple
  • 本文由 发表于 2014年1月30日 14:28:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/21449341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定