How to use zfill() method In Python

  • N no. of zeros to add 
  • Using zfill() inbuild method to add the zeros to the string.
  • Printing the updated string

Python3




# Python code to demonstrate
# adding trailing zeros
# using zfill()
 
# initializing string
test_string = 'GFG'
 
# printing original string
print("The original string : " + str(test_string))
 
# No. of zeros required
N = 4
 
# using zfill()
# adding trailing zero
res = test_string + '0' * N
 
#print result
print("The string after adding trailing zeros : " + str(res))


Output

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

Time complexity: O(N) as it iterates over the string. 

Auxiliary Space: O(N) as we are creating a new 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.

Similar Reads

Using ljust() to  add trailing Zeros to the string

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....

Using format() to  add trailing Zeros to string

...

Without any built-in methods add trailing Zeros to string

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....

Using while loop and += operator

...

Using f-string (Python 3.6+)

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

Using zfill() method

...

Contact Us