How to Add Trailing Zeros to String in Python

In this tutorial, we are going to learn about Add trailing zeros to Python. Basically, sometimes we wish to add zeros at the end of the string; In case of filling the missing bits or any other requirements. This kind of problem can be solved by using certain methods. the methods are:-

using  ljust() method

string = 'Codespeedy'

print("The original string : " + str(string)) 
# No. of zeros
N = 4
x= N + len(string)


res = string.ljust(x, '0') 

# print result 
print("The string after adding trailing zeros: ", res)

Here we initialize the string and the number of zeros that we want to add in the string. N represents the number of string.

Now, using the ljust() method we can add these zeros to the string. it has two parameters where x  gives us the length of the string. what will this method do? it will just go through a string and after that, it will go to the length of the string which we will need and it will check if both are not the same then it will pad those zeros which they have passed a string and after that, it stores in another string.it gives the output as:-

Output:
The original string: Codespeedy
The string after adding trailing zeros:  Codespeedy0000

Read: Python string rjust() and ljust() methods

Using format() method

This is the another method of adding zeros to the end of the string.

string = 'Codespeedy' 
print("The original string : " + str(string))
temp ='{:<014}'
str2 = temp.format(string)
print("The string after adding trailing zeros : ",str2)

Here, we initialize the string at first line, then we print the original string.
In the third line ‘<‘ sign indicates the trailing of the zeros,’0′ sign indicates that we need to add zero and 14 indicates the up to the length of the string after trailing. Now formatting the string and store in another string. it gives the output as:

output:
The original string: Codespeedy
The string after adding trailing zeros: Codespeedy0000

Also read:

Leave a Reply

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