Python String zfill Method - Python Tutorial | Logic Practice
Python Course / Other / Python String zfill Method

Python String zfill Method

BLUF: This lesson on Python String zfill Method provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python String zfill Method

Mastering Python String zfill Method is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience