Search code examples
pythonelementpaddingleading-zero

Python - zfill padding elements with leading Zeros


I have the following values:

sample = ['934254','10031331','331568','10257969','857042','10278189','10275615','10254453']

When I run the below, I get the same output as the original values, the padding of leading zeros does not take place. Please can you advise. Thanks.

res = str(sample).zfill(8)
print(res)

The output should be:

00934254, 10031331, 00331568, etc

Solution

  • What you are doing is turning sample into a string representation of the list then using zfill on it.

    You need to apply the zfill to all the elements. Use a list comprehension for this.

    res = [s.zfill(8) for s in sample]