0

I have a Python list on int types:

list1 = [1, 2, 3, 4, 10, 100]

I need to get another list of the above list values but with equal width like:

list2 = ['001', '002', '003', '004', '010', '100']

I can do this by looping through list1 values, converting them to strings, finding their lengths and appending 0's in-front of the values but this is a bit long process, is there any better way to do this?

Brian
  • 117
  • 4

2 Answers2

2

Use str.zfill

Ex:

list1 = [1, 2, 3, 4, 10, 100]
l = len(str(max(list1)))  #Get max width
result = [str(i).zfill(l) for i in list1]
print(result)

Output:

['001', '002', '003', '004', '010', '100']
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

You can use string formatting:

['{:03.0f}'.format(i) for i in list1]
# ['001', '002', '003', '004', '010', '100']

Or if you don't know the max width in adavance, you can use str.rjust:

w = len(max(map(str, list1), key=len))
list2 = [str(i).rjust(w, '0') for i in list1]
user2390182
  • 72,016
  • 6
  • 67
  • 89