Python | Add trailing zeros to a string

Method # 1: Using ljust()

This task can be accomplished with a simple built-in string function ljust, where we just need to pass no. the element to the right pad is also required of zeros, in this case zero.

# Python3 demo code
# adding trailing zeros
# using ljust ()

  
# initializing string

test_string = `GFG`

  
# print original string

print ( "The original string:" + str (test_string))

 
 there are no zeros

N = 4

 
# using ljust ()
# add trailing zero

res = test_string.ljust (N + len (test_string ), `0` )

  
# print result

print ( "The string after adding trailing zeros:" + str (res))

Exit :

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

Method # 2: Using format()

Formatting Strings using the formatting function can be easily used for this task, we just mention the total number of elements, the number of elements needed to fill, and the direction of the filling, in this case it is correct.

# Python3 demo code
# adding trailing zeros
# using format ()

 
# initialization string

test_string = `GFG`

 
# print original line

print ( "The original string: " + str (test_string))

 
# of zeros required

N = 4

  
# using format ()
# adding a trailing zero
# N for number of items, & # 39; 0 & # 39; for zero and & # 39; & lt; & # 39; for trailing

temp = `{: & lt; 07} `

res = temp. format (test_string)

 
# print result

print ( "The string after adding trailing zeros:" + str (res))

Exit :

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