Python String zfill()
Python String.zfill() is used to fill zeroes at the beginning of this string, until it reaches the given target length of the string. lstrip() method returns a new resulting string and does not modify the original string.
In this tutorial, we will learn the syntax and examples for zfill() method of String class.
Syntax
The syntax to call zfill() method on string x
in Python is
x.zfill(characters)
where
Parameter | Required / Optional | Description |
---|---|---|
len | Required | A number. |
Examples
In the following program, we take a string '3.05'
, and append zeroes at the beginning for a target length of 6 using zfill() method.
Example.py
x = '3.05'
result = x.zfill(6)
print('Original String : ', x)
print('Result String : ', result)
Output
Original String : 3.05
Result String : 003.05
If the length
parameter is less than the length of this string, then the original string value is returned, without any modification.
Example.py
x = '3.05'
result = x.zfill(2)
print('Original String : ', x)
print('Result String : ', result)
Output
Original String : 3.05
Result String : 3.05
Conclusion
In this Python Tutorial, we learned how to fill zeroes at the beginning of the string using zfill() method, with examples.