Python String zfill Method

zfill(width)

Python String zfill Method

The Python zfill function pads the left side of a string with zeros to achieve a specified total length, referred to as width. It returns a string that includes a sign indicator, either + or -, preceding the zeros.

If the specified width is shorter than the length of the string, it will return the string in its original form.

Signature

Example

zfill(width)

Parameters

width : length of the string.

Return

It returns a string.

Let's explore a few instances of the zfill method to grasp its capabilities.

Python String zfill Method Example 1

Consider an illustration where the specified width exceeds the length of the string. In this case, it generates a new string that includes leading zeros, ensuring that the total length matches the defined width.

Example

# Python zfill(width) method
# Declaring variables
text = "Zfill Example"
# Calling Function
str2 = text.zfill(20)
# Displaying result
print(str2)

Output:

Output

0000000Zfill Example

Python String zfill Method Example 2

In this instance, we are providing a width that is shorter than the length of the string, which results in the original string being returned without any leading zeros added.

Example

# Python zfill(width) method
# Declaring variables
text = "Zfill Example"
# Calling Function
str2 = text.zfill(5)
# Displaying result
print(str2)

Output:

Output

Zfill Example

Python String zfill Method Example 3

This illustration explains that the sign, either + or -, appears before the zeroes that are added to the left side of the string. It demonstrates that each value is populated after appending the (+ or -) prefix.

Example

# Python zfill(width) method
# Declaring variables
val = "+100"
val2 = "-200"
val3 = "--Rohan--"
# Calling Function
str2 = val.zfill(10)
str3 = val2.zfill(10)
str4 = val3.zfill(10)

# Displaying result
print(str2)
print(str3)
print(str4)

Output:

Output

+000000100
-000000200
-0-Rohan--

Python Tuple Methods

Input Required

This code uses input(). Please provide values below: