Python str.zfill() function


In Python, the str.zfill() method is used to pad a numeric string with zeros on the left, ensuring that the string has a specified width. This method is particularly useful for formatting numbers, especially when you want them to have a consistent length.

Syntax

str.zfill(width)
  • width: The desired total width of the resulting string after padding. If the original string is longer than this width, it will not be truncated; instead, it will remain unchanged.

Example Usage

  1. Basic usage:
text = "42" result = text.zfill(5) print(result) # Output: "00042"
  1. Negative numbers:

If the string represents a negative number, the minus sign remains at the front, and zeros are added after the minus sign:

text = "-7" result = text.zfill(5) print(result) # Output: "-007"
  1. Width less than original length:

If the specified width is less than the length of the original string, the original string is returned unchanged:

text = "123456" result = text.zfill(3) print(result) # Output: "123456"
  1. Zero padding with strings that contain non-numeric characters:

The zfill() method only works meaningfully with strings that represent numbers. If the string has non-numeric characters, it will behave as expected:

text = "abc" result = text.zfill(5) print(result) # Output: "00abc"
  1. Padding for float representation:

The zfill() method treats the entire string as a sequence of characters, including the decimal point. It does not enforce padding specifically for the numeric value:

text = "3.14" result = text.zfill(6) print(result) # Output: "03.14"

Summary

  • Use str.zfill() to pad a numeric string with leading zeros to ensure it reaches a specified width.
  • It retains the original string if its length exceeds the specified width, and it correctly handles negative numbers by placing zeros after the minus sign.
  • This method is particularly useful in scenarios where consistent string lengths are required, such as formatting numerical outputs.