.zfill()
The .zfill()
method pads a string with zeros on the left to maintain a specific length. It takes an integer argument, and the number of zeros added is determined by the difference between the specified length and the length of the original string.
Note: The
.zfill()
method does not change the string it is used on.
Syntax
result = string.zfill(total_length)
It creates a new string with leading zeros based on the specified integer argument, represented by total_length
. The modified string is stored in the variable result
.
Example
The following example shows how .zfill()
returns a copy of the string with leading zeros.
first_string = "Codecademy"second_string = "@Codecademy"third_string = "cat"print(first_string)print(second_string)# If the argument is less than/equal to string length, output will be the same string.print(first_string.zfill(10))print(second_string.zfill(10))print(first_string.zfill(12))print(second_string.zfill(12))print(third_string.zfill(12))
This will output:
Codecademy@CodecademyCodecademy@Codecademy00Codecademy0@Codecademy000000000cat
Codebyte Example
The following example shows how .zfill()
method helps ensure a specific length for a string, adding zeros to the beginning if the string is shorter than the desired length.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Skill path
Analyze Data with Python
Learn to analyze and visualize data using Python and statistics.Includes 8 CoursesWith CertificateIntermediate13 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours