String zfill() Method in Python

Python String zfill() Method

The zfill() method is a built-in string method in Python. It is used to pad a string with zeros (0) on the left side to a specified width. The method returns a new string with the desired padding applied.

The syntax of the zfill() method is as follows:

string.zfill(width)

Here, string is the original string that you want to pad with zeros, and width is the total width of the resulting string, including both the original content and the additional zeros.

Let's look at some examples to better understand how the zfill() method works:

Example 1:

text = "42"
padded_text = text.zfill(6)
print(padded_text)

Output:

000042

In this example, the original string "42" is padded with four zeros on the left side to achieve a total width of 6 characters.

Example 2:

text = "hello"
padded_text = text.zfill(10)
print(padded_text)

Output:

00000hello

Here, the original string "hello" is padded with five zeros on the left side to achieve a total width of 10 characters.

Example 3:

text = "-7.5"
padded_text = text.zfill(8)
print(padded_text)

Output:

-0007.5

In this case, the original string "-7.5" is padded with three zeros on the left side to achieve a total width of 8 characters.

Keep in mind that if the original string's length is equal to or greater than the specified width, the zfill() method will not perform any padding and will simply return the original string. For example:

text = "hello"
padded_text = text.zfill(4)
print(padded_text)  # Output: hello

The zfill() method is useful when you want to format strings to have a fixed width, especially when working with numeric data or aligning text in columns.