Methods and Functions

Python String zfill()

Some numbers must begin with a zero or a series of zeros. For example, a user ID may require a particular number of zeros at the beginning if it is less than a given amount, in order for all ID numbers to be the same length. We often desire to fill our string with zeros while performing a mathematical calculation or scientific task. If we, do it manually, it will take a long time and there is a good probability that we will make mistakes. So, to accomplish it more precisely and painlessly in Python, we have Python zfill() which is a specific string function that helps perform string handling operations.

Python zfill() function

Definition

  • The Python zfill() function is a string method that returns a copy of the string by padding 0s to the left of the input string.
  • Python zfill() is a built-in string method that pads the‘ 0’ character to the left of the input string and returns it.

Python zfill() Syntax

The syntax followed by Python zfill() is as below:

                    

string.zfill(width)

zfill() Parameters

The zfill() function accepts a single parameter:

  • width – integer value specifying the length of the output string with 0 digits filled to the left of the string until it reaches the specified width.

Note – If the width parameter is not specified, the Python interpreter throws a TypeError exception.

Return Value from zfill()

The zfill() returns a string copy with 0 padded to the left of the characters. The length of the string is determined by the size of the parameter we supplied. As a result, the Python zfill() function’s return type may have two possibilities:

  • Let us assume that the initial length of the string is 5, and the width parameter specified is 10, then the zfill() function will return a copy of the string with 5 Zeros padded to the left of the input string.
  • If the initial length of the string is 10, and the width parameter specified is 5, then the zfill() function does not fill ‘0’ digits to the left, instead, it returns the exact same copy of the original string. The length of the returned string is 10.

Example 1: How zfill() works in Python?

The zfill() function accepts the string and fills it with preceding zeros until it reaches the specified length. Let’s have a look at a few samples to see how the zfill() method in Python works.

Example

                    

# Python program to illustrate zfill()
txt = 'Python programming'
print('Original string:', txt)

print('New string:', txt.zfill(25))
print('New string:', txt.zfill(20))
print('New string:', txt.zfill(18))

Output

                    

Original string: Python programming
New string: 0000000Python programming
New string: 00Python programming
New string: Python programming

Explanation

We simply initialized a string named txt with the string value ‘Python programming’. The length of the string, in this case, is 18 (including the white space). In this simple example, we used the zfill() function 3 times. Initially, we specified the length parameter as 25. As a result, we will get padding of 7 zero at the left or beginning of the string in this scenario.

The second print statement contains zfill() with a width of 20. Hence, we get additional 2 Zeros padded to the left of the string. For the third instance, the width specified is equal to the original string. Hence the zfill() function returns the exact string as output.

Example 2: How zfill() works with Sign Prefix?

If the string begins with a sign (+, -), the Python zfill() function behaves differently. If the string contains a leading + or – sign, zeros are padded after the sign character rather than before it.

Example

                    

# Python program to illustrate zfill()
txt = '+1234'
print('Original string:', txt)
print('New string:', txt.zfill(8))

txt = '-50'
print('Original string:', txt)
print('New string:', txt.zfill(5))

txt = '++hello-world+'
print('Original string:', txt)
print('New string:', txt.zfill(18))

Output

                    

Original string: +1234
New string: +0001234

Original string: -50
New string: -0050

Original string: ++hello-world+
New string: +0000+hello-world+

Alternative Methods to zfill() in Python

There are alternate functions that Python provides in order to carry out the similar tasks which Python zfill() does. They are Python rjust() and Python ljust().

Example

                    

txt = '1234'
print('Original string:', txt)
print('New string:', txt.rjust(8, '0'))

txt = 'Good morning'
print('Original string:', txt)
print('New string:', txt.ljust(20, '0'))

Output

                    

Original string: 1234
New string: 00001234
Original string: Good morning
New string: Good morning00000000

Frequently Asked Questions

Q1. What is zfill in Python?

The Python zfill() function is a string method that returns a copy of the string by padding 0s to the left of the input string. The syntax followed by Python zfill() is as below:

                    

string.zfill(width)

Example

                    

txt = '1234'
print('Original string:', txt)
print('New string:', txt.zfill(8))

txt = 'Good morning'
print('Original string:', txt)
print('New string:', txt.zfill(20))

Output

                    

Original string: 1234
New string: 00001234
Original string: Good morning
New string: 00000000Good morning

Q2. How do you pad a 0 in Python?

Padding a ‘0’ to the string can be done in multiple ways by using Python’s various string handling methods. A few of them are:

  • The Python zfill() function
  • Python rjust()
  • Python ljust()
  • The Python format() function

Example

                    

txt = 'I love Desserts'
print('Original String:', txt)

# pads 0s to the left of the string
print(txt.zfill(20))
# pads 0s to the left of the string by right-justifying the string
print(txt.rjust(20, '0'))
# pads 0s to the right of the string by left-justifying the string
print(txt.ljust(20, '0'))

num = 999
# pads 0s to the left of the string
print(format(num, '06'))

Output

                    

Original String: I love Desserts
00000I love Desserts
00000I love Desserts
I love Desserts00000

000999

Q3. What does str() do in Python?

The str() function returns the object’s string representation. Its syntax is as below:

                    

str(object, encoding, errors)

  • object – The object from which the string representation should be returned. If no arguments are supplied, the empty string is returned.
  • encoding (Optional) – specifies the encoding standard to be used. If no encoding is specified, Python considers UTF-8 as its default encoding standard.
  • errors (Optional) – if any errors occur, it decided how to handle them. The default errors value is ‘strict’. There are 6 types of error responses:
    • strict – default response, which throws a UnicodeDecodeError exception if it fails.
    • ignore – it ignores all the unencodable characters from the result
    • replace – it replaces the unencodable characters from the result with a question mark ‘?’
    • xmlcharrefreplace – substitutes an XML character reference for unencodable Unicode
    • backslashreplace – instead of unencodable Unicode, inserts an \uNNNN escape sequence
    • namereplace – instead of unencodable Unicode, it inserts a \N{…} escape sequence

Example

                    

# Python program to illustrate str()
a = str(50)
print('Value of a:', a)
print('Type of a:', type(a))

b = bytes('Prögræm',  encoding = 'utf-8')
c = str(b, encoding = 'ascii', errors = 'ignore')
print('Value of c:', c)
print('Type of c:', type(c))

Output

                    

Value of a: 50
Type of a: <class 'str'>
Value of c: Prgrm
Type of c: <class 'str'>

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.