A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-string-zfill/ below:

Python String zfill() - GeeksforGeeks

Python String zfill()

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4