Table of Contents
The zfill() method returns a copy of the string with ‘0’ characters padded to the left.
The syntax of zfill() in Python is:
str.zfill(width)
1. zfill() Parameter
zfill() takes a single character width.
The width specifies the length of the returned string from zfill() with 0 digits filled to the left.
2. Return Value from zfill()
zfill() returns a copy of the string with 0 filled to the left. The length of the returned string depends on the width provided.
- Suppose, the initial length of the string is 10. And, the width is specified 15. In this case,
zfill()returns a copy of the string with five ‘0’ digits filled to the left. - Suppose, the initial length of the string is 10. And, the width is specified 8. In this case,
zfill()doesn’t fill ‘0’ digits to the left and returns a copy of the original string. The length of the returned string in this case will be 10.
3. Example 1: How zfill() works in Python?
text = "program is fun" print(text.zfill(15)) print(text.zfill(20)) print(text.zfill(10))
Output
0program is fun 000000program is fun program is fun
If a string starts with the sign prefix ('+', '-'), 0 digits are filled after the first sign prefix character.
4. Example 2: How zfill() works with Sign Prefix?
number = "-290" print(number.zfill(8)) number = "+290" print(number.zfill(8)) text = "--random+text" print(text.zfill(20))
Output
-0000290 +0000290 -0000000-random+text
Related posts:
Python String rstrip()
Python String rpartition()
Converting a Stack Trace to a String in Java
Python String split()
Format ZonedDateTime to String
Python Program to Catch Multiple Exceptions in One Line
Python round()
Python id()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Check Prime Number
Python Iterators
Python Program to Return Multiple Values From a Function
Python Program to Find ASCII Value of Character
Python oct()
String Set Queries
JavaScript Eval: run a code string
Python Program to Find Armstrong Number in an Interval
Python vars()
Python Program to Iterate Over Dictionaries Using for Loop
Python repr()
Python Dictionary popitem()
Python super()
Python Data Types
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Dictionary pop()
Python timestamp to datetime and vice-versa
Python map()
Machine Learning with Python for everyone - Mark E.Fenner
Python Inheritance
Python Program to Swap Two Variables
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Count the Number of Digits Present In a Number