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 strip()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Sort a Dictionary by Value
Python help()
Python String endswith()
Python String format_map()
Convert Character Array to String in Java
Python Program to Convert Two Lists Into a Dictionary
Python Program to Make a Flattened List from Nested List
Python Dictionary get()
Python Shallow Copy and Deep Copy
Python bool()
Python String rfind()
Node.js vs Python for Backend Development
Most commonly used String methods in Java
Python Program to Calculate the Area of a Triangle
Python String ljust()
Python tuple()
Python Program to Split a List Into Evenly Sized Chunks
Python String expandtabs()
Python Program to Get a Substring of a String
Python Program to Get the Full Path of the Current Working Directory
Python Generators
Python Program to Parse a String to a Float or Int
Python sum()
Python Dictionary
Python List index()
Python pow()
Python Program to Add Two Numbers
Python Program to Safely Create a Nested Directory
Python String lstrip()