Open In App

Python String zfill()

Last Updated : 02 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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) 

Output
00042

Explanation:

  • The string "42" is padded with three zeros on the left to make its total length 5.
  • The zfill() method ensures that the string is right-aligned and padded with zeros.

Syntax of zfill() method

string.zfill(width)

Parameters

  • width (required):
    • The total length of the string after padding.
    • If the specified width is less than or equal to the length of the original string, no padding is applied.

Return Type

  • Returns a new string with zeros padded on the left to meet the specified width.

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)  

Output
007

Explanation:

  • The original string "7" has a length of 1.
  • The zfill(3) method pads the string with two zeros on the left to make its total length 3.

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) 

Output
12345

Explanation:

  • The string "12345" already has a length of 5.
  • No padding is added because the string length matches the specified width.

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) 

Output
Python

Explanation:

  • The string "Python" has a length of 6, which is greater than the specified width of 4.
  • The method returns the original string without any changes.

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)) 

Output
00042
-0042

Explanation:

  • For "42", zeros are added to the left to make its total length 5.
  • For "-42", the minus sign is preserved, and zeros are added after the sign to maintain the width.


Next Article
Article Tags :
Practice Tags :

Similar Reads