Python String zfill()

Filed Under: Python

Python String zfill(width) function returns a new string of specified width. The string is filled with 0 on the left side to create the specified width.

If the string starts with sign characters (+,-) then the padding is done after the sign. If the specified width is less than the original string, then the original string is returned.

Python String zfill()

Let’s look at some examples of zfill() function.


s = '100'
print(s.zfill(6))

s = '+100'
print(s.zfill(6))

s = '-100'
print(s.zfill(6))

Output:


000100
+00100
-00100

Let’s see what happens when the specified width is smaller than the string length.


s = '+100'
print(s.zfill(3))

Output: +100

This function is useful when the string is numeric in nature. However, it works with any non-numeric string too.


s = 'abc'
print(s.zfill(6))

s = '+abc'
print(s.zfill(6))

Output:


000abc
+00abc
You can checkout more Python examples from our GitHub Repository.

Official Documentation: zfill()

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages