Add leading zeros to variable in list
Question:
I tried to do some experimenting with variables in lists. Some of numbers wasn’t same length as original input.
For example:
Original: [012, 125, 032]
Result: [12, 125, 32]
How can I add leading zeros to equalise to original values?
I Have tried zfill
and format
but I don’t know how to loop it through.
Answers:
First approach to keep leading zeros in a list of integers could be to use string formatting to convert the integers to strings with leading zeros. Here’s an example code snippet:
original_list = [12, 125, 32]
formatted_list = [f"{x:03d}" for x in original_list]
print(formatted_list)
Second approach could be using the zfill
function in the pandas library:
# importing pandas library
import pandas as pd
# converting the numeric to series to type pandas.Series
ol = pd.Series(original_list)
print(ol)
# to apply zfill function a series should be numeric so converting it to type object i.e string
out = ol.astype(str)
# https://pandas.pydata.org/docs/reference/api/pandas.Series.str.zfill.html
# calling zfill function to see changes i.e value 3 to make all string of equal size by adding leading zero
res = out.str.zfill(3)
Output:
0 12
1 125
2 32
dtype: int64
0 012
1 125
2 032
dtype: object
I tried to do some experimenting with variables in lists. Some of numbers wasn’t same length as original input.
For example:
Original: [012, 125, 032]
Result: [12, 125, 32]
How can I add leading zeros to equalise to original values?
I Have tried zfill
and format
but I don’t know how to loop it through.
First approach to keep leading zeros in a list of integers could be to use string formatting to convert the integers to strings with leading zeros. Here’s an example code snippet:
original_list = [12, 125, 32]
formatted_list = [f"{x:03d}" for x in original_list]
print(formatted_list)
Second approach could be using the zfill
function in the pandas library:
# importing pandas library
import pandas as pd
# converting the numeric to series to type pandas.Series
ol = pd.Series(original_list)
print(ol)
# to apply zfill function a series should be numeric so converting it to type object i.e string
out = ol.astype(str)
# https://pandas.pydata.org/docs/reference/api/pandas.Series.str.zfill.html
# calling zfill function to see changes i.e value 3 to make all string of equal size by adding leading zero
res = out.str.zfill(3)
Output:
0 12
1 125
2 32
dtype: int64
0 012
1 125
2 032
dtype: object