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]
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]
This list comprehension will return what you want
[str(n).zfill(3) for n in a]
as per this thread Display number with leading zeros
you can use str.zfill, you need to turn the numbers into strings first.
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
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']
You can use map and .format to pad zeros:
list(map('{:03}'.format, [1,2,3]))
# ['001', '002', '003']