Python String zfill()

The Python String zfill() method is a built-in function that adds zeros (0) at the beginning of the string until it reaches the specified length and returns the copy of a string.

In this article, we will learn about the Python String zfill() method with the help of examples.

zfill() Syntax

The Syntax of zfill() method is:

str.zfill(width)

zfill() Parameters

The zfill() method does a single parameter width.

  • width – The length of the string returned from zfill() after padding with zeros (0) from the left side of the string. 

zfill() Return Value

The zfill() method returns the copy of a string padded with zeros (0) to the left. The length of the string depends on the width argument provided.

For example, if the initial string length is 10 and the width specified is 15, the zfill() method returns a copy of the string with five zeros (0) filled to the left.

Suppose the initial string length is 10 and the width specified is 5. In this case, the zfill() method does not fill zeros to the string and returns the original string as-is. The length of the string remains 10 in this case.

Note: If the string starts with a prefix like ('+','-'), the zeros are appended after the first sign.

Example 1: How zfill() works in Python?

text = "Python Programming"
print(text.zfill(25))
print(text.zfill(20))

# returns as-is because the width given
# is less than the length of string
print(text.zfill(10))

Output

0000000Python Programming
00Python Programming
Python Programming

Example 2: zfill() in case of Sign Prefix

If the string starts with a prefix like ('+','-'), the zeros are appended after the first sign.

number = "+12345"
print(number.zfill(10))

number = "-5733"
print(number.zfill(8))

text = "--56text-python"
print(text.zfill(20))

Output

+000012345
-0005733
-00000-56text-python
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Python String Lstrip()

Python String lstrip()

Table of Contents Hide lstrip() Syntaxlstrip() Parameterslstrip() Return ValueExample 1: Working of lstrip()Example 2 – How to use lstrip() method in real world? The Python String lstrip() method is a…
View Post
Python String Ljust()

Python String ljust()

Table of Contents Hide ljust() Syntaxljust() Parameters ljust() Return valueExample 1 : Python program to left justify a stringExample 2: ljust() Method With * fillcharExample 3: Returns original string if the…
View Post
Python Enumerate()

Python enumerate()

Table of Contents Hide enumerate() Syntax enumerate() Parametersenumerate() Return ValueExample 1: How enumerate() method works in Python?Example 2: Using Enumerate object in loops The enumerate() in Python is a built-in function that adds…
View Post