Friday, March 15, 2013

Python: Nicest way to pad zeroes to string

Python: Nicest way to pad zeroes to string

Strings:

>>> n = '4'
>>> print n.zfill(3)
>>> '004'
 
And for numbers:
>>> n = 4
>>> print '%03d' % n
>>> 004
>>> print "{0:03d}".format(4)  # python >= 2.6
>>> 004
>>> print("{0:03d}".format(4))  # python 3
>>> 004
String formatting documentation.

 

 








Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment