How to use ljust() to add trailing Zeros to the string In Python
This task can be performed using the simple inbuilt string function of ljust in which we just need to pass the number of zeros required in Python and the element to right pad, in this case being zero.
Python3
# Python3 code to demonstrate # adding trailing zeros # using ljust() # initializing string test_string = 'GFG' # printing original string print ( "The original string : " + str (test_string)) # No. of zeros required N = 4 # using ljust() # adding trailing zero res = test_string.ljust(N + len (test_string), '0' ) # print result print ( "The string after adding trailing zeros : " + str (res)) |
Output
The original string : GFG The string after adding trailing zeros : GFG0000
Output:
The original string : GFG The string after adding trailing zeros : GFG0000
Time Complexity: O(n)
Auxiliary Space: O(n)
Python | Add trailing Zeros to string
Sometimes, we wish to manipulate a string in such a way in which we might need to add additional zeros at the end of the string; in case of filling the missing bits or any other specific requirement. The solution to this kind of problem is always handy and is good if one has knowledge of it. Let’s discuss certain ways in which this can be solved.
Contact Us