Entry
Zero-filling a number
Mar 10th, 2005 00:13
Martin Miller, Nathan Wallace, Hans Nowak, Snippet 254, Andre-John Mas
"""
Packages: text
"""
# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
# Decadent feature: the argument may be a string or a number
# (Use of this is deprecated; it should be a string as with ljust c.s.)
def zfill(x, width):
"""zfill(x, width) -> string
Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated.
"""
if type(x) == type(''): s = x
else: s = `x`
n = len(s)
if n >= width: return s
sign = ''
if s[0] in ('-', '+'):
sign, s = s[0], s[1:]
return sign + '0'*(width-n) + s
# added by PSST
if __name__ == "__main__":
print zfill(42, 7)
# ===================
# Simpler Alternative
#
# use Python's built-in "%" string formatting operator
# which can also handle unicode
def zfill(x, width):
return "%0*d" % (width, int(x))