VOOZH about

URL: https://www.geeksforgeeks.org/python/python-add-leading-zeros-to-string/

⇱ Add Leading Zeros to String - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Add Leading Zeros to String - Python

Last Updated : 11 Jul, 2025

We are given a string and we need to add a specified number of leading zeros to beginning of the string to meet a certain length or formatting requirement.

Using rjust() 

rjust() function in Python is used to align a string to the right by adding padding characters (default is a space) to the left and using this function you can specify the total width of the resulting string and the character used for padding.


Output
The string after adding leading zeros : 0000GFG

Explanation: rjust(4 + len(s), '0') calculates the total width (4 zeros + string length) and pads the string with zeros to the left.

Using zfill()

zfill() function in Python pads a string with leading zeros until it reaches the specified width and if the specified width is less than the string's length, the string remains unchanged.


Output
The string after adding leading zeros: 0000GFG

Explanation: zfill() pads the string with zeros to reach the specified width. Here, 4 + len(s) ensures the string s is padded with 4 zeros.

Using string concatenation

In this method, we are multiplying the 0 as a string with the number of zeros required and using Python concatenation to merge them all.


Output
The string after adding leading zeros: 0000GFG

Using String Formatting

We can directly add required no of zeros using python's string formatting.


Output
The string after adding leading zeros: 0000GFG

Explanation: format string "{:0>{width}}" tells Python to pad the string s with zeros (0) to match the specified total width. The width is calculated as 4 + len(s), ensuring that four zeros are added before the original string.

Using while Loop and += Operator

In this approach, we are using a while loop to manually append the required number of zeros to the string s. The loop runs N times, adding one zero per iteration, and then the original string s is concatenated to the result.


Output
The string after adding leading zeros: 0000GFG

Using string.ljust()

string.ljust(width, fillchar) method in Python pads the string with the specified fillchar (default is a space) on the left side until the string reaches the specified width.


Output
The string after adding leading zeros: GFG0000

Using itertools.repeat() and join() method

itertools.repeat("0", N) repeats the string '0' for N times and the join() method is used to concatenate the repeated zeros into a single string, which is then concatenated with the original string s to add the leading zeros.


Output
The string after adding leading zeros: 0000GFG
Comment