Open In App

Python | Add leading Zeros to string

Improve
Improve
Like Article
Like
Save
Share
Report

Here, we will learn how to pad or add leading zeroes to the output as per the requirements. Let’s discuss certain ways in which this problem can be solved in Python.

Example: 

Input: GFG
Output: 0000GFG
Explanation: Added four zeros before GFG.

Display a String With Leading Zeros in Python

Add leading Zeros to the string using rjust() 

This function offers a single-line way to perform this particular task. Hence can easily be employed on any string whose padding we need to be done. We can specify the amount of padding required. 

Python3




# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string :"
      + str(test_string))
 
# No. of zeros required
N = 4
 
# using rjust()
# adding leading zero
res = test_string.rjust(N +
                        len(test_string), '0')
 
# print result
print("The string after adding leading zeros : "
      + str(res))


Output

The original string :GFG
The string after adding leading zeros : 0000GFG

Time Complexity: O(n)
Auxiliary Space: O(n)

Add leading Zeros to the string using zfill() 

This is yet another way to perform this particular task, in this function we don’t need to specify the letter that we need to pad, this function is exclusively made to pad zeros internally and hence recommended. 

Python3




# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string : " + str(test_string))
 
# No. of zeros required
N = 4
 
# using zfill()
# adding leading zero
res = test_string.zfill(N + len(test_string))
 
# print result
print("The string after adding leading zeros : " + str(res))


Output

The original string : GFG
The string after adding leading zeros : 0000GFG

Add leading Zeros to the string using concatenation

In this method, we are multiplying the 0 as a string with the number of zeros the user wants and using Python concatenation to merge them all.

Python3




# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string : " +
      str(test_string))
 
# No. of zeros required
N = 4
 
 
# adding leading zero
x = '0'*N
res = x+test_string
 
# print result
print("The string after adding leading\
zeros : " + str(res))


Output

The original string : GFG
The string after adding leadingzeros : 0000GFG

Add leading Zeros to the string using formatting:

This code defines a function add_leading_zeros() that takes in a string s and an integer num_zeros and returns a new string with num_zeros number of zeros added to the start of the string.

The function uses string formatting to pad the input string s with zeros on the right side (i.e., at the start of the string). The width parameter specifies the total width of the resulting string, and the :0> part tells Python to pad the string with zeros on the right side.

The code then tests the function by initializing the string s to “GFG” and the number of zeros num_zeros to 4. It prints the original string and then calls the add_leading_zeros() function to add leading zeros to the string. The resulting padded string is then printed.

Python3




def add_leading_zeros(s, num_zeros):
    # use string formatting to pad the string with zeros
    formatted_string = "{:0>{width}}".format(s, width=num_zeros + len(s))
    return formatted_string
 
# test the function
s = "GFG"
num_zeros = 4
 
# print the original string
print("The original string :", s)
 
# add leading zeros to the string
padded_string = add_leading_zeros(s, num_zeros)
 
# print the padded string
print("The string after adding leading zeros :", padded_string)
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original string : GFG
The string after adding leading zeros : 0000GFG

Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), since a new string is created to store the padded string.

Add leading zeroes to string using while loop and += operator

Python3




s = "GFG"
num_zeros = 4
 
# print the original string
print("The original string :", s)
 
# add leading zeros to the string
i=0
padded_string=""
while(i<num_zeros):
    padded_string+="0"
    i+=1
     
padded_string+=s
# print the padded string
print("The string after adding leading zeros :", padded_string)


Output

The original string : GFG
The string after adding leading zeros : 0000GFG

Time Complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), since a new string is created to store the padded string.

Another Method:

The below implementation uses the multiplication operator to create a string of leading zeroes with the number of zeroes equal to the desired leading_zero minus the length of the input string, and concatenates it with the original string.

Python3




def add_leading_zeroes(s, leading_zero):
    return f"{'0'*leading_zero}{s}"
 
 
# Test the function
s = "GFG"
leading_zero = 4
 
# print the original string
print("The original string :", s)
print("The string after adding leading zeros :", add_leading_zeroes(s, leading_zero))


Output

The original string : GFG
The string after adding leading zeros : 0000GFG

Time Complexity: O(1)
Auxiliary Space: O(n), as we are creating a new string with n zeroes.

Add leading Zeros to the string using string.ljust() method:

1.Initialize the input string ‘test_string’.
2.Print the original string using the print() function.
3.Initialize the number of zeros required ‘N’.
4.Use the ljust() method of the input string to add leading zeros.
a. The first argument to the ljust() method is the total width of the resulting string, which is the sum of the length of the input string and the number of zeros required.
b. The second argument is the character to be used for padding, which is ‘0’ in this case.
5.Store the resulting string in the variable ‘res’.
6.Print the resulting string using the print() function.

Python3




# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string: " + test_string)
 
# number of zeros required
N = 4
 
# using ljust()
# adding leading zeros
res = test_string.ljust(N + len(test_string), '0')
 
# print result
print("The string after adding leading zeros: " + res)


Output

The original string: GFG
The string after adding leading zeros: GFG0000

Time Complexity:
The time complexity of the given code is O(N), since the ljust() method performs a single pass over the input string.

Space Complexity:
The space complexity of the given code is O(N), where N is the number of zeros required, since the resulting string may have up to N extra characters due to the leading zeros.

Adding leading zeroes to the string using itertools.repeat() and join() methods

Approach

  1. Used itertools.repeat() to repeat ‘0’ N times and the join the object returned by empty string(using join method)
  2. Concatenate the joined string and test_string and store it in res
  3. Display res

Python3




import itertools
# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string: " + test_string)
 
# number of zeros required
N = 4
 
# adding leading zeros
res= "".join(itertools.repeat("0",N))+test_string
 
# print result
print("The string after adding leading zeros: " + res)


Output

The original string: GFG
The string after adding leading zeros: 0000GFG

Time Complexity : O(N) N – value of N

Auxiliary Space : The space complexity of the given code is O(N), where N is the number of zeros required, since the resulting string may have up to N extra characters due to the leading zeros.



Last Updated : 09 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads