Strings with zero-padded values and other string formatting examples in Python
Assume you want to convert a number to a string but you want to pad the smaller numbers with zeros so that all strings have the same length (for example, '0009', '0069' and '0132'). There are many ways to do this but in Python, there is a very elegant way using string formatting:
Since the
anumber = 9
thestr = "%04d" % (anumber)
print thestr
0009
anumber = 69
thestr = "%04d" % (anumber)
print thestr
0069
anumber = 132
thestr = "%04d" % (anumber)
print thestr
0132
anumber = 12541
thestr = "%04d" % (anumber)
print thestr
12541
Since the
format()
function is preferred (since Python 2.6 I think), you might want to use it instead (see here):
anumber = 69
thestr = "{0:0>4}".format(anumber)
print thestr
0069
thestr = "{0:0<4}".format(anumber)
print thestr
6900
thestr = "{0:0<8}".format(anumber)
print thestr
69000000
thestr = "{0:0^8}".format(anumber)
print thestr
00069000
thestr = "{0:-^8}".format(anumber)
print thestr
---69---
Comments
Post a Comment