What is zfill() method in Python?



The zfill() method in Python is used to pad a string with leading zeros to achieve a specified total length. If the string is already longer than the specified length, zfill() does nothing.

Syntax

Following is the syntax for the zfill() method

string.zfill(width) 

Consistent File Naming

Consistent file naming with leading zeros is crucial for sequential processing scripts because it ensures correct sorting and handling of files.

Example

Here, even though i ranges from 1 to 10, each number is formatted to have three digits with leading zeros, ensuring consistent filename length.

for i in range(1, 11): filename = f"file_{str(i).zfill(3)}.txt" print(filename) 

Following is the output for the above code-

file_001.txt file_002.txt file_003.txt file_004.txt file_005.txt file_006.txt file_007.txt file_008.txt file_009.txt file_010.txt 

Formatting Serial Numbers

Serial numbers often need to be of a fixed length. zfill() ensures that shorter serial numbers conform to the required format.

Example

In this case, zfill(8) ensures the serial number is 8 characters long, padding with zeros on the left.

serial_number = "1234" formatted_serial = serial_number.zfill(8) print(formatted_serial) 

Following is the output for the above code-

00001234 

Time Representation

When displaying time in a specific format (e.g., HH:MM:SS), zfill() can be used to ensure that single-digit hours, minutes, and seconds are displayed with a leading zero.

Example

This ensures that the time is always displayed in the HH:MM:SS format, even when the individual components are single digits.

hour = "8" minute = "3" second = "2" formatted_time = f"{hour.zfill(2)}:{minute.zfill(2)}:{second.zfill(2)}" print(formatted_time) 

Following is the output for the above code-

08:03:02 

IP Address Formatting

When dealing with IP addresses, you might need to ensure each segment is padded to a certain length for display or processing.

Example

Here, each segment of the IP address is padded to three digits by using the zfill() method, which can be useful in certain network applications or displays.

ip_segment1 = "192" ip_segment2 = "168" ip_segment3 = "1" ip_segment4 = "5" formatted_ip = f"{ip_segment1.zfill(3)}.{ip_segment2.zfill(3)}.{ip_segment3.zfill(3)}.{ip_segment4.zfill(3)}" print(formatted_ip) 

Following is the output for the above code-

192.168.001.005 
Updated on: 2025-03-06T18:51:51+05:30

296 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements