left padding zeroes on a string...

M.E.Farmer mefjr75 at hotmail.com
Fri Mar 25 17:40:53 EST 2005


Your first conversion works fine.
string1 = '32'
string2 = "%04s" % (string1)
print string2
'   32'
Notice that it returns a string with spaces padding the left side.
If you want to pad a number with 0's on the left you need to use
zfill()
'32'.zfill(4)
'0032'
Be sure to study up on string methods, it will save you time and
sanity.
Py> dir('')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__',
'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__',
'__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode',
'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum',
'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
Py> help(''.zfill)
Help on built-in function zfill:

zfill(...)
    S.zfill(width) -> string

    Pad a numeric string S with zeros on the left, to fill a field
    of the specified width.  The string S is never truncated.
Hth,
M.E.Farmer




More information about the Python-list mailing list