1

e.g. I have this array

list=['123', '4', '56']

I want to add '0' in the beginning of list array that has 1 or 2 digit. So the output will be:

list=['123', '004', '056']

5 Answers5

3

Use zfill method:

In [1]: '1'.zfill(3)
Out[1]: '001'

In [2]: '12'.zfill(3)
Out[2]: '012'
Osman Mamun
  • 2,864
  • 1
  • 16
  • 22
2

Using a list comprehension, we can prepend the string '00' to each number in the list, then retain the final 3 characters only:

list = ['123', '4', '56']
output = [('00' + x)[-3:] for x in list]
print(output)  # ['123', '004', '056']
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

As per How to pad zeroes to a string?, you should use str.zfill:

mylist = ['123', '4', '56']
output = [x.zfill(3) for x in mylist]

Alternatively, you could (though I don't know why you would) use str.rjust

output = [x.rjust(3, "0") for x in mylist]

or string formatting:

output = [f"{x:0>3}" for x in mylist]
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
  • If it does then this question is a duplicate. I just put his code in a list comprehension and listed alternatives because Tim asked me to. – Boris Verkhovskiy Jun 02 '21 at 15:36
0

I'd say this would be a very easy to read example, but not the shortest.

Basically, we iterate through the lists elements, check if the length is 2 or 1. Based on that we will add the correct amount of '0'

lst=['123', '4', '56']
new = []
for numString in lst:
    if len(numString) == 2:
        new.append('0'*1+numString)
    elif len(numString) == 1:
        new.append('0'*2+numString)
    else:
        new.append(numString)
print(new)

Also I kind of had to include it (list comprehension).But this is barely readable,so I gave the above example. Look here for list comprehension with if, elif, else

lst=['123', '4', '56']
new = ['0'*1+numString if len(numString) == 2 else '0'*2+numString if len(numString) == 1 else numString  for numString in lst]
print(new)

output

['123', '004', '056']
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
-2

trying into integer and add preceding zero/s then convert into a string and replace the element in the same position and the same list

list=["3","45","111"]
n=len(list)
for i in range(0,n):
        list[i] = str(f"{int(list[i]):03}")

You can check the solution for this in link