Add leading Zeros to Python Program string

PythonServer Side ProgrammingProgramming

We may sometimes need to append zeros as string to various data elements in python. There may the reason for formatting and nice representation or there may be the reason for some calculations where these values will act as input. Below are the methods which we will use for this purpose.

Using format()

Here we take a DataFrame and apply the format function to the column wher we need to append the zeros as strings. The lambda method is used to apply the function repeatedly.

Example

import pandas as pd
string = {'Column' : ['HOPE','FOR','THE','BEST']}
dataframe=pd.DataFrame(string)
print("given column is ")
print(dataframe)
dataframe['Column']=dataframe['Column'].apply(lambda i: '{0:0>10}'.format(i))
print("\n leading zeros is")
print(dataframe)

Output

Running the above code gives us the following result −

given column is
    Column
0     HOPE
1     FOR
2     THE
3    BEST

   leading zeros is
         Column
0    000000HOPE
1    0000000FOR
2    0000000THE
3    000000BEST

Using rjust

The right justify function helps us in making the given values right justified by using the parameter we supply to the rjust function. In this example, we add three zeros to a value using rjust function. The number of zeros to be added can be made dynamic.

Example

val = '98.6 is normal body temperature'
print("The given string is :\n " + str(val))
#Number of zeros to be added
i = 3
result = val.rjust(i + len(val), '0')
print("adding leading zeros to the string is :\n" + str(result))

Output

Running the above code gives us the following result −

The given string is :
98.6 is normal body temperature
adding leading zeros to the string is :
00098.6 is normal body temperature
raja
Published on 18-Feb-2020 10:27:50
Advertisements