Faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 8 people (63%) answered Yes
Recently 4 of 6 people (67%) answered Yes

Entry

Zero-filling a number

Sep 15th, 2009 02:19
jick heir, 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))
http://sundhedernaeringguide.blogspot.com/
http://zdravevyzivypruvodce.blogspot.com/
http://guidasalutenutrizione.blogspot.com/
http://gesundheiternahrungpflege.blogspot.com/
http://soinssantenutrition.blogspot.com/
http://zdravljeprehranavodic.blogspot.com/
http://healthnutritionhoito.blogspot.com/
http://hlhnutgr.blogspot.com/
http://gezondheidvoedinggids.blogspot.com/
http://taplalkozas-egeszsegugyikezikonyv.blogspot.com/
http://hlthnutbg.blogspot.com/