In this tutorial, you’ll learn how to use Python’s zfill method to pad a string with leadering zeroes. You’ll learn how the method works and how to zero pad a string and a number. You’ll also learn how to use the method in Pandas as well as how to use sign prefixes, such as + or -, in your padding. Finally, you’ll learn some alternatives to the Python zfill
method, which give you different flexibility. These alternatives include the rjust
function and using string formatting for padding and aligning your text.
The Quick Answer: Python zfill Pads a String with Leading Zeroes
# Using Python zfill to pad a string
a_string = 'datagy'
print(a_string.zfill(10))
# Returns: 0000datagy
Table of Contents
Python zfill: Overview
The Python zfill
method is a string method that returns a copy of the string left filled with the '0'
character to make a character the length of a given width.
The method takes a single parameter, width
. This parameter is used to assign the width of the desired string. Let’s take a look at the method:
str.zfill(
width=
)
The width parameter is mandatory. The method will raise a TypeError
if no width is passed in. Similarly, the method will raise a TypeError
if a floating point value is passed, rather than an integer value. Later in this tutorial, you’ll learn what happens when certain types of widths are passed.
In the next section, you’ll learn a brief overview of why you may want to pad a string in Python.
Why Zero Pad a String in Python
There are many reasons why you might want to zero pad a string in Python. For example, in many legacy finance applications, data systems will expect an input that is a certain length. In order to be able to insert data into these systems, you may need to zero pad your data.
Similarly, when importing data into Python, a key may be inferred as a number, thereby removing leading zeroes. This then creates challenges in terms of being able to merge datasets later on. By zero padding a number-like string allows you to safely reformat your data to be able to merge it across dataframes.
How to Use Python zfill to Pad a String in Python with Zeros
The Python zfill
method is used to create a copy of a string with zeros padding the string to a particular width. Let’s try an example:
# Using Python zfill to pad a string
a_string = 'datagy'
print(a_string.zfill(10))
# Returns: 0000datagy
We can see that the method returned a string with the zeros padding the left side.
Remember, Python strings are immutable, meaning that they cannot be changed. We can verify this by applying the method and then pritning the original string:
# Using Python zfill to pad a string
a_string = 'datagy'
a_string.zfill(10)
print(a_string)
# Returns: datagy
If we wanted to “update” our string (remember, this won’t actually update the string, but rather create a new one), we need to re-assign it. Let’s see what this looks like:
# Using Python zfill to pad a string
a_string = 'datagy'
a_string = a_string.zfill(10)
print(a_string)
# Returns: 0000datagy
How Do We Modify Our String?
We can see that we were able to successfully re-assign the string to itself with the .zfill()
method applied.
Wondering what data type the .zfill()
method returns? We can do this easily by using the type
function. Let’s see what this returns:
# Checking the Return Type of the .zfill() Method
a_string = 'datagy'
print(type(a_string.zfill(10)))
# Returns: <class 'str'=""></class>
Unsurprisingly, the zfill method returns a string data type.
What Happens If the Width is Shorter than the String?
Why don’t we take a look at what happens when the width we pass in is shorter than the original string? Let’s take a look at what happens:
# Zero Padding a String with a Shorter Length
a_string = 'datagy'
print(a_string.zfill(4))
# Returns: datagy
If the width is either shorter or the same length as our original string, the method simply returns a copy of the original string.
How to Use Python zfill With Numbers
Because the zfill
method is a string method, it can only be used with strings. There may be times when you want to pad a number with leading zeroes. Let’s see what happens when we try to apply the zfill method to an integer:
# Attempting to Pad an Integer with Zeroes
number = 13
number.zfill(5)
# Returns: AttributeError: 'int' object has no attribute 'zfill'
We can see that when we attempt to apply the method to an integer, that an AttributeError
is raised.
In order to prevent this error, we need to first convert the integer into a string. We can do this using the str()
function. Let’s see what this looks like:
# Zero Padding an Integer in Python
number = 13
print(str(number).zfill(7))
# Returns: 0000013
It’s important to note that this is no longer an integer! It’s actually resulted in a string. This means that we can’t perform any operations you may normally associate with numbers, such as addition.
In the next section, you’ll learn how to use the zfill method in a Pandas dataframe to pad an entire dataframe column.
How to Zero Pad a Column in Pandas with zfill
There may be times when you want your Pandas dataframes’ values to be left-padded with zeros. Pandas actually implements the zfill
method directly in a Pandas dataframe, meaning that we can apply the function in a vectorized format.
To see how this works, let’s first import a sample Pandas dataframe:
# Importing a Sample Pandas Dataframe
import pandas as pd
df = pd.DataFrame.from_dict({
'ID': [1,2,3,4,5,6,7,8,9],
'Sales': [100, 120, 110, 120, 145, 95, 80, 75, 135]
})
print(df.head())
# Returns:
# ID Sales
# 0 1 100
# 1 2 120
# 2 3 110
# 3 4 120
# 4 5 145
Let’s say we wanted to pad the values of ID column. We can simply apply the str.zfill()
method to our dataframe column. Since these values are immutable, we need to be mindful to reassign the values to itself.
# Zero Padding a Pandas dataframe column
df['ID'] = df['ID'].astype('str').str.zfill(5)
print(df.head())
# Returns:
# ID Sales
# 0 00001 100
# 1 00002 120
# 2 00003 110
# 3 00004 120
# 4 00005 145
We can see how easy it is to pad a column with zeroes. Because the values in our column aren’t strings, we first need to convert them to strings using the .astype()
method. If our column already was made of strings, we could skip this step.
## How to Zero Pad with Sign Prefixes in Python
The Python zfill
method actually works really well when we want to assign sign prefixes, such as a + or – sign to a zero padded string. We simply need to include the sign prefix that we want and Python will take care of the rest.
Let’s take a look at what this looks like:
# Zero Padding in Python with Sign Prefixes
a_number = '+13'
print(a_number.zfill(5))
# Returns: +0013
We can see that Python intelligently moved the sign prefix to the front of the string! This allows us to easily ensure that sign prefixes are respected.
One important thing to note here is that the sign prefix is included in the width of the string. Since we passed in a width of 5, we may have expected the returned copy to include three zeroes. However, because the full width is 5 including the sign, only two additional zeroes were included.
In the following two sections you’ll learn two alternatives to the zfill
method!
Right Pad a String with Python rjust
There may be times that you want to pad a string but you don’t want to have it filled with zero values. In these cases, it can be helpful to use the rjust
string method.
The rjust
method is applied to a string and takes two parameters: (1) the width of the resulting string and (2) the character to use to pad the original string.
Let’s use a space to pad our string using the rjust
method:
# Using .rjust to Pad a Python String
a_string = 'datagy'
print(a_string.rjust(10, ' '))
# Returns:
# datagy
The benefit of this approach is that we can use any character to pad our strings with.
In the final section, you’ll learn how to use string formatting to pad a string.
Right Pad a String with Python String Formatting
In this final section, you’ll learn how to use Python string formatting to pad a string from the left.
Python makes this quite easy. Let’s see how we can use traditional string formatting to pad a string:
# Pad a String with String Formatting
a_string = 'datagy'
print('{:0>10}'.format(a_string))
# Returns: 0000datagy
We use the :0
to ask Python to use 0s to pad our string and the >10
to indicate to pad from the left for a width of ten.
Similarly, we can use Python f-strings to pad a string:
# Pad a String with F-Strings
a_string = 'datagy'
print(f'{a_string:0>10}')
# Returns: 0000datagy
This approach is a bit more readable as it makes it immediately clear what string you’re hoping to pad.
Conclusion
In this tutorial, you learned how to use the Python zfill method to left-pad a string with zeroes. You also learned how to pad numbers with zeroes and how to pad a Pandas dataframe column. Finally, you learned some alternatives to the zfill method. These alternatives included the rjust
method and Python string formatting.
To learn more about the Python str.zfill()
method, check out the official documentation here.
Additional Resources
To learn about related topics, check out the tutorials below: