Friday, March 4, 2011

Python: Nicest way to pad zeroes to string

What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?

From stackoverflow
  • For numbers:

    print "%05d" % number
    

    See also: Python: String formatting.

    EDIT: It's worth noting that as of yesterday, this method of formatting is deprecated in favour of the format string method:

    print("{0:05d}".format(number)) # or
    print(format(number, "05d"))
    

    See PEP 3101 for details.

  • Strings:

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

    And for numbers:

    >>> n = 4
    >>> print '%03d' % n
    >>> '004'
    
  • width = 10
    x = 5
    print "%0*d" % (width, x)
    > 0000000005
    

    See the print documentation for all the exciting details!

  • Just use the rjust method of the string object.

    This example will make a string of 10 characters long, padding as necessary.

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

0 comments:

Post a Comment