Python String zfill() Function
The String zfill()
method returns a new string obtained by padding the string with zeros on the left side to ensure it reaches a specified length width
.
If width
is less than or equal to string length, then the original string is returned.
This method is particularly useful for formatting numbers or strings to a fixed width, especially when dealing with numeric strings that need to be aligned for display or processing purposes.
Syntax
my_string.zfill(width)
zfill() Parameters
Python String zfill()
function parameters:
Parameter | Condition | Description |
---|---|---|
width | Required | The length of the string with zeros padded to the left |
zfill() Return Value
Python String zfill()
function returns a copy of the string with 0
filled to the left.
The length of the returned string depends on the width
parameter:
- If
width
is less than or equal to string length, then the original string is returned. - If
width
is greater than string length, then the string with padding is returned.
Examples
Example 1: Zero Padding on the Left of a String with zfill()
This example demonstrates the basic usage of the zfill()
method by padding a string with zeros to reach a specified length.
For example, let's pad with zeros to make it 5 characters long:
my_str = "123"
result = my_str.zfill(5)
print(result) # Output: 00123
output
00123
Of course zfill()
method works with any type of character (and not only with digits):
my_str = "abc"
result = my_str.zfill(5)
print(result) # Output: 00abc
output
00abc
Example 2: Zero Padding on the Left of a String with Sign Prefix
If the string contains a leading sign +
(plus) or -
(minus), the zero digits are correctly padded after the sign character.
my_str_positive = "+123"
my_str_negative = "-123"
result_positive = my_str_positive.zfill(5)
result_negative = my_str_negative.zfill(5)
print(result_positive) # Output: +0123
print(result_negative) # Output: -0123
output
+0123
-0123
The leading +
(plus) or -
sign is counted as a character in the string!
my_str = "+123"
print(my_str.zfill(4)) # Output: +123
print(my_str.zfill(5)) # Output: +0123
output
+123
+0123
Example 3: Zero Padding on the Left of a String with smaller width
If the original string is already longer than the specified width
parameter, then no padding is added.
For example, let's try to pad a string of length 6 with zeros with width=5
:
my_str = "123456"
result = my_str.zfill(5)
print(result) # Output: 123456
output
123456
Equivalent method to Zero Padding on the Left a String
You can obtain the same result of zfill()
method by using the format()
method.
An example using zfill()
method:
my_str = "25"
result = my_str.zfill(6)
print(result) # Output: 000025
output
000025
and equivalent example that uses format()
method:
my_str = '25'
result = '{:0>6}'.format(my_str)
print(x) # Output: 000025
output
000025