0
0
PythonHow-ToBeginner · 3 min read

How to Pad String with Zeros in Python: Simple Guide

In Python, you can pad a string with zeros using the str.zfill(width) method, which adds zeros to the left until the string reaches the specified width. Alternatively, you can use formatted string literals like f"{value:0{width}d}" to pad numbers with zeros.
📐

Syntax

The main ways to pad strings with zeros in Python are:

  • str.zfill(width): Pads the string on the left with zeros until it reaches width.
  • f"{value:0{width}d}": Uses formatted string literals to pad an integer value with zeros to the left.
  • "{:0{width}d}".format(value): Uses the format() method for zero-padding integers.
python
padded = '42'.zfill(5)
formatted = f"{42:05d}"
format_method = "{:05d}".format(42)
💻

Example

This example shows how to pad a number string and an integer with zeros to make them 5 characters long.

python
number_str = '42'
padded_str = number_str.zfill(5)

number_int = 42
padded_int_fstring = f"{number_int:05d}"
padded_int_format = "{:05d}".format(number_int)

print(padded_str)
print(padded_int_fstring)
print(padded_int_format)
Output
00042 00042 00042
⚠️

Common Pitfalls

Common mistakes when padding strings with zeros include:

  • Using zfill() on non-string types without converting them first.
  • Confusing padding width with the number of zeros to add (width is total length).
  • Trying to pad floats directly with zfill(), which works only on strings.

Always convert numbers to strings before using zfill(), or use formatted strings for numbers.

python
wrong = 42
# wrong.zfill(5)  # This will cause an error because 42 is int

# Correct ways:
correct_str = str(42).zfill(5)
correct_format = f"{42:05d}"
📊

Quick Reference

Summary of zero-padding methods:

MethodDescriptionExample
str.zfill(width)Pads string on left with zeros to total length width'42'.zfill(5) → '00042'
f"{value:0{width}d}"Pads integer with zeros to length width using f-stringf"{42:05d}" → '00042'
"{:0{width}d}".format(value)Pads integer with zeros using format method"{:05d}".format(42) → '00042'

Key Takeaways

Use str.zfill(width) to pad strings with zeros on the left.
For numbers, prefer formatted strings like f"{value:0{width}d}" for zero-padding.
Always convert numbers to strings before using zfill().
The width parameter defines the total length after padding, not the number of zeros added.
Avoid using zfill() directly on non-string types to prevent errors.