Python String zfill() (original) (raw)

Last Updated : 02 Jan, 2025

zfill() method in Python is used to pad a string with zeros (0) on the left until it reaches a specified width. In this article, we’ll see how zfill() method works.

Python `

s = "42"

padded_text = s.zfill(5) print(padded_text)

`

Explanation:

Table of Content

Syntax of zfill() method

string.zfill(width)

Parameters

Return Type

Examples of String zfill() method

1. Padding a shorter string

Let’s see how zfill() behaves with a string shorter than the specified width:

Python `

s = "7" padded_text = s.zfill(3) print(padded_text)

`

Explanation:

2. String equal to the specified width

What happens when the string length matches the specified width?

Python `

s = "12345"

padded_text = s.zfill(5) print(padded_text)

`

Explanation:

3. String longer than the specified width

Let’s see how zfill() handles a string longer than the specified width:

Python `

s = "Python"

padded_text = s.zfill(4) print(padded_text)

`

Explanation:

4. Using zfill() with negative and positive numbers

When dealing with strings representing numbers, the zfill() method correctly handles the sign:

Python `

#positive and negative numbers s1 = "42" s2 = "-42"

print(s1.zfill(5))
print(s2.zfill(5))

`

Explanation: