Python String zfill() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

Python String zfill() method

The zfill() method in Python concatenates zeros (0) at the beginning of the string, until it reaches the specified length.

If the value of the len parameter is less than the length of the original string, no filling is done.

Syntax of zfill() method
string.zfill(len)

len: The length of the new string after filling(Required)
Example 1

Code

a = "Pylenin"
b = "Pylenin loves Python"
c = "@pylenin"

print(a.zfill(10))
print(b.zfill(10))
print(c.zfill(10))

Output

000Pylenin
Pylenin loves Python
00@pylenin
Example 2 - Working with sign prefix (+ and -)

If your strings are prefixed with signs like + and -, then the filling happens after the sign.

Code

a = "+Pylenin"
b = "-Pylenin"

print(a.zfill(10))
print(b.zfill(10))

Output

+00Pylenin
-00Pylenin

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide