Yandex

Python String zfill() Method – Pad String with Zeros


Python String zfill() Method

The zfill() method in Python is used to pad a numeric string with leading zeros, so that the resulting string reaches a specified length. It's especially useful when formatting numbers like invoice IDs, codes, or timestamps.

Syntax

string.zfill(width)

Parameter:

  • width – The total length of the resulting string (including leading zeros).

Returns:

  • A copy of the string left-padded with zeros to make it at least width characters long.

Example 1: Simple Zero Padding

text = "42"
print(text.zfill(5))
00042

Example 2: zfill() with Negative Numbers

text = "-42"
print(text.zfill(5))
-0042

Note: The negative sign is preserved in its original position.

Example 3: No Padding if Already Long Enough

text = "12345"
print(text.zfill(4))
12345

The string remains unchanged because its length is already more than the specified width.

Use Cases

  • Formatting IDs with fixed length (e.g., invoice IDs like INV000123)
  • Preparing data for export to systems that require zero-padded numbers
  • Display time values like 05 instead of 5

Common Mistakes

  • Using zfill() on non-string types like integers will raise an error. Convert to string first.
  • Confusing zfill() with rjust() or ljust() which pad with spaces by default.

Interview Tip

zfill() is handy in problems requiring fixed-width formatting or normalization of numeric string data before comparison.

Summary

  • zfill() pads the string on the left with 0s until it reaches the specified length.
  • It preserves the sign position for negative numbers.
  • Only works on string types — use str() on numbers before calling zfill().

Practice Problem

Write a program that asks the user for a number and prints it as a 6-digit zero-padded string.

user_input = input("Enter a number: ")
print("Padded Number:", user_input.zfill(6))

Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M