Add leading Zero Python [duplicate]

You can use the builtin str.zfill method, like this

my_string = "1"
print my_string.zfill(2)   # Prints 01

my_string = "1000"
print my_string.zfill(2)   # Prints 1000

From the docs,

Return the numeric string left filled with zeros in a string of length
width. A sign prefix is handled correctly. The original string is
returned if width is less than or equal to len(s).

So, if the actual string’s length is more than the width specified (parameter passed to zfill) the string is returned as it is.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)