zfill() Function in Python pads string on the left with zeros to the required width. We will be padding the integer or string with preceding zeros or leading zeros till the desired length is obtained using zfill() function.
Syntax of zfill() Function in Python
width – width of the string. The Final width which we would get after filling zeros.
Example of zfill() Function in Python
zfill() function takes up the string and fills the string with preceding zeros until the desired length is obtained. we have shown two different examples below to depict the example of zfill() function in python.
#zfill() for positive number string number1="345" print number1.zfill(4) # zfill() for negative number string number2="-675" print number2.zfill(6)
so the output with preceding zeros filled will be
‘-00675’
Example of zfill() Function in Python for Text String:
In the below example we will be using zfill() function to pad the text string to desired length.
##### zfill() for Text String text="This is sample text" text.zfill(40)
so the output with preceding zeros filled to the text will be
ALTERNATIVE METHOD TO zfill() function in python
leading and trailing zeros using rjust() and ljust() function:
#### rjust() for adding leading zeros number1="345" number1.rjust(7, '0') ###### Add trailing zeros ljust number3="345.2" number3.ljust(7, '0')
In the first example we are using rjust() function to add leading zeros to the string to the total length of 7. In the second example we are using ljust() function to add trailing zeros after the decimal until we get the total length of 7 digit. so the result will be
‘345.200’
Add leading zeros using format function : Method 1
Format function takes up the numeric value as argument and pads them with preceding zeros until the desired length is reached. Here in our case we will padding till length 10.
#### add leading zeros using format function number1 = 345 number2 = -675 #Method 1 '{:010}'.format(number1) '{:010}'.format(number2)
so the result will be
‘-000000675’
Add leading zeros using format function : Method 2
Format function takes up the numeric value as argument and pads them with preceding zeros until the desired length is reached. Here in our case we will padding till length 7.
#### add leading zeros using format function number1 = 345 number2 = -675 #Method 2 print(format(number1, '07')) print(format(number2, '07'))
so the result will be
‘-000675’