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 Set discard()
Python Program to Check If a List is Empty
Converting String to Stream of chars
Python Program to Find the Factorial of a Number
Python Program to Get Line Count of a File
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Find the Largest Among Three Numbers
Python String expandtabs()
Python dir()
APIs in Node.js vs Python - A Comparison
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Converting String to Stream of chars
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python min()
Python Program to Get File Creation and Modification Date
Python String startswith()
Python sum()
Python Program to Get the Last Element of the List
Python String isupper()
Python Dictionary get()
Python vars()
Python dict()
Python super()
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Create a Long Multiline String
Python frozenset()
Python String istitle()
Python Program to Find Hash of File
Python format()
Python String index()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Data Structures and Algorithms - Benjamin Baka