In Python programming, adding leading zeros (zeros left-padding) to a string is useful in various scenarios, such as when maintaining consistent formatting, sorting values, or ensuring proper alignment in numerical data or timestamps. It helps with chronological ordering, uniform length, and consistent naming conventions.
This concise, example-based article will show you 3 different techniques to add leading zeros to a given string in Python.
Using f-strings
If you just want to add a single or a fixed number of zeros to the left of a string and don’t care about the width (the number of columns a string occupies when displayed on a terminal or a screen) of the result, you can do like this:
s1 = "1"
s2 = "2"
padded_s1 = f"0{s1}"
print(padded_s1) # 01
padded_s2 = f"00{s2}"
print(padded_s2) # 002
In case you want to get results with a fixed desired width, you can use the format specifier like this:
my_string = "12345"
my_number = 1111
# Pad my_string with zeros to a width of 7
print(f"{my_string:0>7}") # 0012345
# Pad my_number with zeros to a width of 10
print(f"{my_number:0>10}") # 0000001111
Using f-strings is very flexible. In the example above, we not only used a string as input but also used a number.
Using the str.zfill() method
In this approach, we will call the zfill()
method on the input string and pass an integer as an argument. This argument determines the width of the returned string. If it is less than or equal to the width of the input string, no zeros will be added.
Example:
s1 = '123'
print(s1.zfill(5))
s2 = '1234'
print(s2.zfill(5))
Output:
00123
01234
Using the str.rjust() method
This method can right justify a string. Below is its syntax:
str.rjust(width[, fillchar])
Where:
width
is an integer that determines the width of the output string.fillchar
is the character that fills the missing space. In the context of this tutorial, it will be set to0
.
Similar to the zfill()
method, the original string will be returned if width
is less than or equal to the width of the original string.
Example:
text = '1234'
# pad the string with 0s on the left
# the result will always contain 10 characters
padded_text = text.rjust(10, '0')
print(padded_text)
Output:
0000001234
Additional information about the width of a string
In Python, the width of a string is not the same as its length (which can be calculated by using the len()
function). To measure the width of a string, you can use the wcwidth module:
pip install wcwidth
Sample usage:
from wcwidth import wcswidth
text = "Sling Academy"
print(wcswidth(text)) # 13
You can find more details in this article.