2

I have a list a:

a = [45,2, ... ,123,98]

How can I convert all numbers to three-digit numbers by adding zeros in front of one or two-digit numbers? This would create a new list like:

b = [045,002, ... , 123,098]
NoLand'sMan
  • 534
  • 1
  • 3
  • 17

5 Answers5

0

This list comprehension will return what you want

[str(n).zfill(3) for n in a]
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
0

as per this thread Display number with leading zeros

you can use str.zfill, you need to turn the numbers into strings first.

Juan
  • 117
  • 6
0

You can't represent integers with a leading 0. To do so as strings, do this:

for i in range(len(a)):
  helper = str(a[i])
  while len(helper) < 3:
    helper = "0" + helper
  a[i] = helper
Julian Chan
  • 446
  • 2
  • 8
0
def func(num):
    '''
    Adds leading 0s to numbers with < 3 digits, and returns as string
    '''
    if len(str(num))<3:
        num = '0'*(3-len(str(num)))+str(num)
    return str(num)

a = [45,2,123,98]

b = []
for num in a:
    b.append(func(num))

print(b)

>>> ['045', '002', '123', '098']

You can also skip the for loop and apply the function to each element in the list a in the following manner:

b = [_ for _ in map(func,a)]
print(b)
>>>  ['045', '002', '123', '098']
Kristada673
  • 3,512
  • 6
  • 39
  • 93
0

You can use map and .format to pad zeros:

list(map('{:03}'.format, [1,2,3]))                                                                                                                                                  
# ['001', '002', '003']
oppressionslayer
  • 6,942
  • 2
  • 7
  • 24