Python 3 – String zfill() Method
In Python, zfill() is a built-in method used to pad a string with leading zeros. It takes a single argument representing the length of the returned string, which includes the original string and any padded zeros.
Syntax
string.zfill(length)
The zfill() method is a string method that returns a new string with leading zeros added to the original string. The method modifies the original string in place.
Parameters
The zfill() method takes a single parameter:
– length – This specifies the width of the returned string. It should be an integer value.
Return Value
The zfill() method returns a copy of the original string, padded with zeros to the specified length.
Examples
Example 1: Padding leading zeros with zfill() method
string = "Python"
padded_string = string.zfill(10)
print(padded_string)
Output:
000Python
In the above example, the zfill()
method pads the string with leading zeros to make the total length of the string to 10 characters.
Example 2: Using zfill() method with negative numbers
string = "-3.14"
padded_string = string.zfill(8)
print(padded_string)
number = -123
padded_string = str(number).zfill(6)
print(padded_string)
Output:
-0003.14
-00123
In the above example, the zfill()
method pads the string with leading zeros to make the total length of the string to 8 and 6 characters respectively while preserving the negative sign.
Example 3: Padding leading zeros with variable number of digits
numbers = [3, 54, 324, 6321]
for number in numbers:
print(str(number).zfill(5))
Output:
00003
00054
00324
06321
In this example, we demonstrate how to pad the number with leading zeros to ensure all numbers have the same number of digits.
Conclusion
Python’s zfill()
method is a useful way of padding a number or string with leading zeros. It is especially helpful when working with formatted tables or output that requires a consistent width. Through this tutorial, you have learned how to call the zfill()
method on a string and understood how it works with the help of examples.