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
- 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
- Basic usage:
- Negative numbers:
If the string represents a negative number, the minus sign remains at the front, and zeros are added after the minus sign:
- Width less than original length:
If the specified width is less than the length of the original string, the original string is returned unchanged:
- 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:
- 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:
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.