The zfill Method in Python: Adding Leading Zeros to a String

Pads a string with zeros on the left to reach a specified minimum length.

zfill(width)

  • width -- desired minimum length of the resulting string.

The original string is not shortened, even if it has fewer characters than the specified length. Leading + and - signs remain at the start of the string.

''.zfill(3)  # 000
'1'.zfill(4)  # 0001
'1'.zfill(0)  # 1
'-1'.zfill(4)  # -001
'a'.zfill(4)  # 000a
'-a'.zfill(4)  # -00a

You can achieve a similar result using the rjust() method with 0 as the second argument. To add zeros to the right, use ljust() with 0 as the second argument.