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

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python String Count()

Python String count()

Table of Contents Hide count() Syntaxcount() Parameter count() Return ValueExample 1: Count the number of occurrences of a given substring without optional argumentsExample 2: Count the number of occurrences of a…
View Post
Python String To Array

How To Convert Python String To Array

Table of Contents Hide Python String to Arraysplit() Syntaxsplit() ParametersExample 1: Split the string using the default argumentsExample 2: Split the string using the specific characterPython String to Array of…
View Post