How to use format() to add trailing Zeros to string In Python
String formatting using the format() function can be used to perform this task easily, we just mention the number of elements total, element needed to pad, and direction of padding, in this case right.
Python3
# Python3 code to demonstrate # adding trailing zeros # using format() # initializing string test_string = 'GFG' # printing original string print ( "The original string : " + str (test_string)) # No. of zeros required N = 4 # using format() # adding trailing zero # N for number of elements, '0' for Zero, and '<' for trailing temp = '{:<07}' res = temp. format (test_string) # print result print ( "The string after adding trailing zeros : " + str (res)) |
The original string : GFG The string after adding trailing zeros : GFG0000
Time complexity: O(1) as it does not involve any loops or iterations.
Auxiliary space:O(1) as it only involves a fixed amount of memory used to store the input string, the integer value N, and the formatted output string.
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