code_junkie

Python: Nicest way to pad zeroes to string

Nov 12th, 2011
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.50 KB | None | 0 0
  1. >>> n = '4'
  2. >>> print n.zfill(3)
  3. >>> '004'
  4.  
  5. >>> n = 4
  6. >>> print '%03d' % n
  7. >>> '004'
  8.  
  9. print "%05d" % number
  10.  
  11. print("{0:05d}".format(number)) # or
  12. print(format(number, "05d"))
  13.  
  14. >>> t = 'test'
  15. >>> t.rjust(10, '0')
  16. >>> '000000test'
  17.  
  18. width = 10
  19. x = 5
  20. print "%0*d" % (width, x)
  21. > 0000000005
  22.  
  23. >>> n = 3
  24. >>> str(n).zfill(5)
  25. '00003'
  26. >>> n = '3'
  27. >>> str(n).zfill(5)
  28. '00003'
  29. >>> n = '3.0'
  30. >>> str(n).zfill(5)
  31. '003.0'
  32.  
  33. >>> a = 6340
  34. >>> b = 90210
  35. >>> print '%05d' % a
  36. 06340
  37. >>> print '%05d' % b
  38. 90210
Add Comment
Please, Sign In to add comment