left padding zeroes on a string...

Kent Johnson kent37 at tds.net
Fri Mar 25 23:46:10 CET 2005


cjl wrote:
> Hey all:
> 
> I want to convert strings (ex. '3', '32') to strings with left padded
> zeroes (ex. '003', '032')

In Python 2.4 you can use rjust with the optional fill argument:
  >>> '3'.rjust(3, '0')
'003'

In earlier versions you can define your own:
  >>> def rjust(s, l, c):
  ...   return ( c*l + s )[-l:]
  ...
  >>> rjust('3', 3, '0')
'003'
  >>> rjust('32', 3, '0')
'032'

Kent



More information about the Python-list mailing list