rank vote url
77 340 83 533 url

给字符串填充0

有什么方法可以给字符串左边填充0,这样就可以有一个特定长度.


字符串:

  1. >>> n = '4'
  2. >>> print n.zfill(3)
  3. >>> '004'

对于数字:

  1. >>> n = 4
  2. >>> print '%03d' % n
  3. >>> 004
  4. >>> print format(4, '03') # python >= 2.6
  5. >>> 004
  6. >>> print "{0:03d}".format(4) # python >= 2.6
  7. >>> 004
  8. >>> print("{0:03d}".format(4)) # python 3
  9. >>> 004

  1. >>> t = 'test'
  2. >>> t.rjust(10, '0')
  3. >>> '000000test'

原文: https://taizilongxu.gitbooks.io/stackoverflow-about-python/content/77/README.html