Method # 1: Using rjust()
The rjust
function offers a one-line a way to accomplish this specific task. Hence, it can be easily used for any line that we need to fill. We can specify the required amount of padding.
# Python3 demo code # adding leading zeros # using rjust () # initialization string test_string = ’GFG’ # print the original string print ( "The original string:" + str (test_string)) # of zeros required < / p> N = 4 # using rjust () # adding leading zero res = test_string.rjust (N + len (test_string), ’0’ ) # print result print ( "The string after adding leading zeros:" + str (res)) |
Output:
The original string: GFG The string after adding leading zeros: 0000GFG
Method # 2: Using zfill()
This is another way to accomplish this specific task, in this function we do not need to specify the letter that we need to complete, this function is solely for filling zeros inside and therefore is recommended.
# Python3 code for demonstration # adding leading zeros # using zfill () # initialization string test_string = ’GFG’ # print the original line print ( "The original string:" + str (test_string)) # Of zeros required N = 4 # using zfill () # add leading zero res = test_string.zfill (N + len (test_string)) # print result print ( "The string after adding leading zeros:" c ode> + str (res)) |
Output:
The original string: GFG The string after adding leading zeros: 0000GFG
Python | Add leading zeros to string Python functions: Questions
Python | Add leading zeros to string String Variables: Questions