Python的print格式化输出还支持‘字符串’精度控制

1.格式化输出整数
[python]strHello = "the length of (%s) is %d" %('Hello World',len('Hello World'))
print strHello
#输出果:the length of (Hello World) is 11
[/python]
2.格式化输出16制整数

#%x --- hex 十六进制
#%d --- dec 十进制
#%d --- oct 八进制

[python]
nHex = 0x20
print "nHex = %x,nDec = %d,nOct = %o" %(nHex,nHex,nHex)
#输出结果:nHex = 20,nDec = 32,nOct = 40
#使用整数的各个制打印同一个数
[/python]
3.格式化输出浮点数(float)
[python]
import math
#default
print "PI = %f" % math.pi
#width = 10,precise = 3,align = left
print "PI = %10.3f" % math.pi
#width = 10,precise = 3,align = rigth
print "PI = %-10.3f" % math.pi
#前面填充字符
print "PI = %06d" % int(math.pi)
#六位填0
#输出结果
#PI = 3.141593
#PI = 3.142
#PI = 3.142
#PI = 000003
#浮点数的格式化,精度、度和
[/python]
4.格式化输出字符串(string)
[python]
#precise = 3
print "%.3s " % ("jcodeer")
#precise = 4
print "%.*s" % (4,"jcodeer")
#width = 10,precise = 3
print "%10.3s" % ("jcodeer")
#输出结果:
#jco
#jcod
# jco
#同于字符串也存在精度、度和[/python]

Author Info :
  • From:Python的print格式化输出还支持‘字符串’精度控制
  • URL:https://blog.ihipop.com/2010/10/1759.html
  • Please Reserve This Link,Thanks!
  • 《Python的print格式化输出还支持‘字符串’精度控制》上有6条评论

    1. @Demon 他不是没学过,而是那啥那啥了,

      请注意这并不是 print 的所谓格式化输出,
      而是 python 字符串方法,

      去在 python 命令行执行下
      >>> '%10s' % 'WTF'

    回复 Shellexy 取消回复

    您的电子邮箱地址不会被公开。 必填项已用*标注