How to Pad a String with Zeros in Python

Pad a string to a fixed width by left-filling it with zeros using the built-in str.zfill method.

Easy Python 3.9+ Aug 9, 2026 Strings & text 16 views 0 copies

Python code

8 lines
Python 3.9+
def pad_zeros(s, width):
    return s.zfill(width)

if __name__ == "__main__":
    print(repr(pad_zeros("42", 6)))
    print(repr(pad_zeros("-7", 5)))
    print(repr(pad_zeros("hello", 10)))
    print(repr(pad_zeros("123", 3)))

Output

stdout
'000042'
'-0007'
'00000hello'
'123'

How it works

The str.zfill(width) method returns a copy of the string left-filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+' or '-') is handled correctly: the zeros appear after the sign, so '-7'.zfill(5) becomes '-0007'. If the original string is already at least as long as width, it is returned unchanged, as shown with '123'.zfill(3). Since zfill is a method on str, it works for any string, not just numeric ones.

Common mistakes

  • Using ljust('0') which pads on the right instead of the left
  • Confusing zfill with string formatting that might not handle signs the same way
  • Forgetting that zfill does not truncate; it only pads when the width is larger than the string length

Variations

  1. Use f-string formatting for integers: f'{42:05d}'
  2. Use str.format with format spec: '{:0>6}'.format('42')

Real-world use cases

  • Formatting numeric IDs or order numbers to a consistent length for display or sorting.
  • Preparing fixed-width fields for file exports like CSV or log lines where alignment matters.
  • Creating zero-padded date or time components (e.g., '07' for month) before concatenating strings.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.