0
0
PythonHow-ToBeginner · 3 min read

How to Use zfill in Python: Pad Strings with Leading Zeros

In Python, zfill(width) is a string method that pads the string on the left with zeros until it reaches the specified width. It is useful for formatting numbers as strings with leading zeros.
📐

Syntax

The zfill method is called on a string and takes one argument:

  • width: The total length of the resulting string after padding.

If the original string is shorter than width, zeros are added to the left. If it is already equal or longer, the string is returned unchanged.

python
string.zfill(width)
💻

Example

This example shows how zfill adds leading zeros to a number represented as a string to make it 5 characters long.

python
number = "42"
padded_number = number.zfill(5)
print(padded_number)  # Output: 00042

# If string is longer than width, it stays the same
long_number = "123456"
print(long_number.zfill(5))  # Output: 123456
Output
00042 123456
⚠️

Common Pitfalls

One common mistake is trying to use zfill on non-string types like integers directly, which causes an error. Always convert numbers to strings first.

Also, zfill only adds zeros on the left and does not truncate strings longer than the specified width.

python
num = 7
# Wrong: num.zfill(3)  # AttributeError: 'int' object has no attribute 'zfill'

# Right:
num_str = str(num)
padded = num_str.zfill(3)
print(padded)  # Output: 007
Output
007
📊

Quick Reference

zfill(width) pads a string with zeros on the left to reach width length.

  • Input: string
  • Output: string padded with leading zeros
  • Does not change strings longer than width
  • Convert non-strings to string before using

Key Takeaways

Use zfill(width) to pad strings with leading zeros to a fixed length.
Always convert numbers to strings before using zfill.
zfill does not truncate strings longer than the specified width.
It is useful for formatting numbers like IDs or codes with leading zeros.