In this tutorial, we’ll learn what Python string zfill() method is and how to properly use it. We’ll go through multiple Python code examples to understand how zfill method works.
Outline
- Introduction: Python String zfill() Method
- Syntax of zfill() Method
- Example 1: zfill() Method applied on a Python String
- Example 2: Python String zfill() Method Return Value
- Conclusion
Introduction: Python String zfill() Method
This method returns a string with number ‘0’ padded to its left side only if this method’s argument value is greater than the length of original string.
Syntax of zfill() Method
string.zfill(stringLength)
- Python string zfill method take a single argument. We can specify the length of new string using this argument. It takes a number.
- This method returns a string after adding digit ‘0’ to its left(if the value of argument is greater than the original string’s length).
Example 1: zfill() Method applied on a Python String
print('Python Program'.zfill(10)) print('Python Program'.zfill(20)) print('Python Program'.zfill(26)) print('Python Program'.zfill(17)) print(''.zfill(5)) // empty string print('Python'.zfill()) // zfill takes only one argument and it is required
Output
Python Program 000000Python Program 000000000000Python Program 000Python Program 00000 TypeError: zfill() takes exactly one argument (0 given)
This is how Python string zfill method works. You can try it with even more examples to better understand the working of this method.
Example 2: Python String zfill() Method Return Value
val='Python Programming Language' returnedValue=val.zfill(34) print(returnedValue) // returned string print(val) // original string
Output
0000000Python Programming Language // returned string Python Programming Language // original string
We can see that Python string zfill() method has returned a new string having digit ‘0’ padded to its left and it will be padded only if the argument value is greater than the length of original string. It not, then only the string will be returned.
Conclusion
To conclude this tutorial, hope you now have a detailed practical understanding of how to properly use Python string zfill method. I’d be very happy to receive your feedback on this post. Thank you for reading it.
You may like to read:
How To Use Python String Title Method [Python Easy Guide]
How To Use Python String IsDecimal() Method – Easy Python Code Guide
How To Easily Use Python String RPartition Method [Detailed Python Guide]
How To Easily Use Python String Split Method [Detailed Python Guide]
How To Properly Use Python String StartsWith Method [Detailed Python Guide]