![]() |
VOOZH | about |
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.
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.
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.
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.
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.
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.
The string after adding leading zeros: 0000GFG
We can directly add required no of zeros using python's string formatting.
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.
while Loop and += OperatorIn 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.
The string after adding leading zeros: 0000GFG
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.
The string after adding leading zeros: GFG0000
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.
The string after adding leading zeros: 0000GFG