Python String zfill() Method


The Python String zfill() method is used to fill the string with zeroes on its left until it reaches a certain width; else called Padding. If the prefix of this string is a sign character (+ or -), the zeroes are added after the sign character rather than before.

The Python String zfill() method does not fill the string if the length of the string is greater than the total width of the string after padding.

Note: The zfill() method works similar to the rjust() method if we assign '0' to the fillchar parameter of the rjust() method.

Syntax

Following is the syntax for Python String zfill() method −

str.zfill(width)

Parameters

  • width − This is final width of the string. This is the width which we would get after filling zeros.

Return Value

This method returns padded string.

Example

If we apply the zfill() method to the input string, the padded string with zeroes is obtained as the result

The following example shows the usage of Python String zfill() method. Here, we are inputting a string, "this is string example....wow!!!", as the input and invoking the zfill() method on it twice, with different arguments '40' and '50'. The return value in each case will be the string with the leading zeroes upto given width.

#!/usr/bin/python

str = "this is string example....wow!!!";
print(str.zfill(40))
print(str.zfill(50))

When we run above program, it produces following result −

00000000this is string example....wow!!!
000000000000000000this is string example....wow!!!

Example

If the width parameter of zfill() method is less than the string length, the original string is returned as a result.

In the following example, we are creating a string, say "Welcome to Tutorialspoint" and call the zfill() method on this string. The input string is

str = "Welcome to Tutorialspoint";
print(str.zfill(20))

When we run above program, it produces following result −

Welcome to Tutorialspoint

Example

If we create a string that holds a date as the input, the zfill() method is called to return the string in a standard date format (in DD-MM-YYYY).

In this example, we are creating three input strings: day, month and year, which does not follow the standard date format (DD/MM/YYYY) when concatenated together. So, we call the zfill() method on each of these strings, to add leading zeroes wherever necessary and obtain the date in the correct format. The resultant string is printed as output.

def perfect_date(day, month, year):
   day = day.zfill(2)
   month = month.zfill(2)
   year = year.zfill(4)
   date = day + '/' + month + '/' + year
  print("The perfect date (DD-MM-YYYY) is: " + date)

day = '2'
month = '6'
year = '2022'
perfect_date(day, month, year)

The output for the program above is displayed as follows −

The perfect date (DD-MM-YYYY) is: 02/06/2022
python_strings.htm
Advertisements