How do I pad a string with zeros in Python?

To pad a string with zeros in Python, you can use several methods depending on whether you’re working with strings or numeric types (e.g., integers). Below are the most common approaches:

1. Using str.zfill() (for strings)

The zfill() method pads a numeric string with leading zeros to a specified width.
Key points:

  • Works on strings (e.g., "123").
  • Automatically handles signs (+ or -), placing them at the start.
  • If the string is longer than the specified width, it returns the original string.

Example:

s = "42"
padded = s.zfill(5)  # Pad to length 5
print(padded)        # Output: "00042"

s_negative = "-3"
padded_negative = s_negative.zfill(5)
print(padded_negative)  # Output: "-0003"

2. Using format() or f-strings (for numbers or strings)

For numbers (integers) or strings, use Python’s string formatting with 0> alignment and a fixed width.

For strings:

s = "7"
padded = format(s, "0>5")  # Pad to length 5
print(padded)              # Output: "00007"

# Using f-strings:
padded_f = f"{s:0>5}"
print(padded_f)            # Output: "00007"

For integers:

num = 42
padded_num = format(num, "05d")  # Pad to 5 digits
print(padded_num)               # Output: "00042"

# Using f-strings:
padded_num_f = f"{num:05d}"
print(padded_num_f)             # Output: "00042"

3. Using Variable Padding Width

Dynamically set the padding width using nested formatting:

width = 10
num = 7

# For integers:
padded = f"{num:0{width}d}"
print(padded)  # Output: "0000000007"

# For strings:
s = "hello"
padded_str = f"{s:0>{width}}"
print(padded_str)  # Output: "00000hello"

4. Handling Non-Numeric Strings

To pad a non-numeric string with zeros (e.g., "apple"), use string formatting:

text = "apple"
padded_text = f"{text:0>10}"  # Pad to length 10
print(padded_text)            # Output: "00000apple"

Key Differences Between Methods

MethodWorks ForHandles SignsVariable Width Support
str.zfill(width)Strings (numeric)
format()/f-stringsStrings/numbers❌ (unless explicitly formatted)

Common Pitfalls

  • Type Errors: Ensure numeric values are converted to strings before using zfill():
  num = 42
  padded = str(num).zfill(5)  # Convert to string first
  • Overflow: If the original string/num is longer than the padding width, no truncation occurs:
  "123456".zfill(3)  # Output: "123456" (unchanged)

Summary Table

GoalCode Example
Pad a numeric string"42".zfill(5)"00042"
Pad an integerf"{7:05d}""00007"
Pad a string with variable widthf"{'9':0>{width}}""00009" (if width=5)
Handle negative numbers"-3".zfill(5)"-0003"

Choose the method that best fits your data type and use case!

Leave a Reply

Your email address will not be published. Required fields are marked *