Go 格式化输出


Printf() 的输出格式设置

Go 提供了几种可以与Printf()功能。


一般格式输出

以下格式可用于所有数据类型:

Verb Description
%v Prints the value in the default format
%#v Prints the value in Go-syntax format
%T Prints the type of the value
%% Prints the % sign

示例

package main
import ("fmt")

func main() {
  var i = 15.5
  var txt = "Hello World!"

  fmt.Printf("%v\n", i)
  fmt.Printf("%#v\n", i)
  fmt.Printf("%v%%\n", i)
  fmt.Printf("%T\n", i)

  fmt.Printf("%v\n", txt)
  fmt.Printf("%#v\n", txt)
  fmt.Printf("%T\n", txt)
}

结果:

15.5
15.5
15.5%
float64
Hello World!
"Hello World!"
string
亲自试一试 »

整数格式化动词

以下动词可以与整数数据类型一起使用:

Verb Description
%b Base 2
%d Base 10
%+d Base 10 and always show sign
%o Base 8
%O Base 8, with leading 0o
%x Base 16, lowercase
%X Base 16, uppercase
%#x Base 16, with leading 0x
%4d Pad with spaces (width 4, right justified)
%-4d Pad with spaces (width 4, left justified)
%04d Pad with zeroes (width 4

示例

package main
import ("fmt")

func main() {
  var i = 15
 
  fmt.Printf("%b\n", i)
  fmt.Printf("%d\n", i)
  fmt.Printf("%+d\n", i)
  fmt.Printf("%o\n", i)
  fmt.Printf("%O\n", i)
  fmt.Printf("%x\n", i)
  fmt.Printf("%X\n", i)
  fmt.Printf("%#x\n", i)
  fmt.Printf("%4d\n", i)
  fmt.Printf("%-4d\n", i)
  fmt.Printf("%04d\n", i)
}

结果:

1111
15
+15
17
0o17
f
F
0xf
  15
15
0015
亲自试一试 »


字符串格式化动词

以下动词可以与字符串数据类型一起使用:

Verb Description
%s Prints the value as plain string
%q Prints the value as a double-quoted string
%8s Prints the value as plain string (width 8, right justified)
%-8s Prints the value as plain string (width 8, left justified)
%x Prints the value as hex dump of byte values
% x Prints the value as hex dump with spaces

示例

package main
import ("fmt")

func main() {
  var txt = "Hello"
 
  fmt.Printf("%s\n", txt)
  fmt.Printf("%q\n", txt)
  fmt.Printf("%8s\n", txt)
  fmt.Printf("%-8s\n", txt)
  fmt.Printf("%x\n", txt)
  fmt.Printf("% x\n", txt)
}

结果:

Hello
"Hello"
   Hello
Hello
48656c6c6f
48 65 6c 6c 6f
亲自试一试 »

布尔格式化动词

以下动词可以与布尔数据类型一起使用:

Verb Description
%t Value of the boolean operator in true or false format (same as using %v)

示例

package main
import ("fmt")

func main() {
  var i = true
  var j = false

  fmt.Printf("%t\n", i)
  fmt.Printf("%t\n", j)
}

结果:

true
false
亲自试一试 »

浮点格式化动词

以下动词可与 float 数据类型一起使用:

Verb Description
%e Scientific notation with 'e' as exponent
%f Decimal point, no exponent
%.2f Default width, precision 2
%6.2f Width 6, precision 2
%g Exponent as needed, only necessary digits

示例

package main
import ("fmt")

func main() {
  var i = 3.141

  fmt.Printf("%e\n", i)
  fmt.Printf("%f\n", i)
  fmt.Printf("%.2f\n", i)
  fmt.Printf("%6.2f\n", i)
  fmt.Printf("%g\n", i)
}

结果:

3.141000e+00
3.141000
3.14
  3.14
3.141
亲自试一试 »