Open In App

How to Pad a String to a Fixed Length with Zeros in Python

Last Updated : 27 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Padding a string to a fixed length with zeros in Python is basically adding leading zeros until it reaches the desired size.

Using zfill() Method

The simplest way to pad a string with zeros is by using Python’s built-in zfill() method. This method adds zeros to the left of a string until it reaches the desired length.

Python
a = "123"

result = a.zfill(6)  
# Pad '123' with zeros to make the length 6
print(result) 

Output
000123

Let's explore various other methods we can use to pad a string to a fixed length with zeroes in python are:

Using rjust()

The rjust() method is another efficient option for padding strings. It is slightly more versatile than zfill() since it allows padding with any character, but for zero-padding.

Python
s = "123"

# Use rjust() to pad the string 's' 
#with zeros on the left to make its total length 6
padded = s.rjust(6, '0')
print(padded) 

Output
000123

Using String Formatting with str.format()

When we want more control over how the string is padded, we can use the str.format() method. This method allows us to specify the total length and add zeros to the left.

Python
a = "123"

# Pad '123' with zeros to make the length 6
result = "{:0>6}".format(a)  
print(result) 

Output
000123

Using f-strings

Using Python 3.6 or newer, f-strings provide a very clean and easy way to pad strings. We can specify the total length and use zeros to pad the string.

Python
a = "123"

# Pad '123' with zeros to make the length 6
result = f"{a:0>6}"  
print(result) 

Output
000123
  • In the f-string f"{a:0>6}", 0 is the padding character, > means to pad from the left, and 6 is the total length.

Using String Concatenation (Manual Approach)

If we want to manually handle how zeros are added, we can use string concatenation. This method gives us full control over the padding.

Python
a = "123"

length = 6
# Calculate how many zeros to add
zeros_needed = length - len(a)  
# Add zeros to the left
result = "0" * zeros_needed + a  
print(result) 

Output
000123

Next Article

Similar Reads