Change language

Python | Add leading zeros to string

| |

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:" + 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

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method