What is zfill() in Python?
The zfill() method in Python appends the 0 characters to the left side of the string according to a specified length.
Syntax
The syntax of the function is as follows:
string.zfill(length)
Parameters
This function takes one parameter, which defines the final length of the required string.
To do that, it appends the 0 characters on the left to fulfill the given length.
Return value
It returns a string with the 0 characters added to the left side of the string.
The
zfill()method does not affect the original string. It creates its copy.
Code
The code below appends the zeros to the string, and the length becomes 15 (as specified).
It is important to note if either - or + is present at the start of the string.
The zeros are attached after the sign as shown in the second and third examples.
string = "Welcome"x = string.zfill(15)print(x)print("The length of string is:",len(x))# with signs, zeros move ahead of signsignNum = "-147"print(signNum.zfill(7))signNum = "+147"print(signNum.zfill(7))