Python | Add leading Zeros to string
Sometimes, during the string manipulation, we are into a problem where we need to pad or add leading zeroes to the string as per the requirements. This problem can occur in web development. Having shorthands to solve this problem turns to be handy in many situations. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using rjust()
rjust function offers a single line way to perform this particular task. Hence can easily be employed to any string whose padding we need to be done. We can specify the amount of padding required.
# Python3 code to demonstrate # adding leading zeros # using rjust() # initializing string test_string = 'GFG' # printing original string print("The original string : " + str(test_string)) # No. of zeros required 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)) |
The original string : GFG The string after adding leading zeros : 0000GFG
Method #2 : Using zfill()
This is yet another way to perform this particular task, in this function we don’t need to specify the letter that we need to pad, this function is exclusively made to pad zeros internally and hence recommended.
# Python3 code to demonstrate # adding leading 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 leading zero res = test_string.zfill(N + len(test_string)) # print result print("The string after adding leading zeros : " + str(res)) |
The original string : GFG The string after adding leading zeros : 0000GFG
Recommended Posts:
- Python | Remove leading zeros from an IP address
- Python | Add trailing Zeros to string
- Python | Remove trailing/leading special characters from strings list
- numpy.zeros() in Python
- Python | sympy.zeros() method
- Create a Numpy array filled with all zeros | Python
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Check if given string can be formed by concatenating string elements of list
- Python | Merge Tuple String List values to String
- Python | Check if string ends with any string in given list
- Python | Sorting string using order defined by another string
- Python | Sort each String in String list
- String slicing in Python to rotate a string
- Python | Check if a given string is binary string or not
- numpy matrix operations | zeros() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


