4

I'm trying to prepend zeros to each number in a list if it isn't a the necessary number of digits.

    lst = ['1234','2345']
    for x in lst:
        while len(x) < 5:
            x = '0' + x
    print(lst)

Ideally this would print ['012345', '02345']

Coby
  • 136
  • 1
  • 2
  • 8
  • A better example would be if `lst = ['1234', '23456']`. How do we `print(lst)` and get `['01234', '23456']` – Coby Jun 28 '17 at 14:30
  • Ultimately it was a combination of the answers that was successful. `lst = ['1234','2345'] newlst = [] for i in lst: i = i.zfill(5) newlst.append(i) print(newlst)' – Coby Jun 28 '17 at 14:41

5 Answers5

13

You can use zfill:

Pad a numeric string s on the left with zero digits until the given width is reached

lst = ['1234','2345']
[s.zfill(5) for s in lst]
# ['01234', '02345']

Or use format method with padding and alignment:

["{:0>5}".format(s) for s in lst]
# ['01234', '02345']
Psidom
  • 209,562
  • 33
  • 339
  • 356
3

You code doesn't do the job because strings in python are immutable, see this for more info Why doesn't calling a Python string method do anything unless you assign its output?

You could you enumerate in this case like this:

lst = ['1234','2345', "23456"]
for i, l in enumerate(lst):
  if len(l) < 5:
    lst[i] = '0' + l
print(lst)

['01234', '02345', '23456']

developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • Hi Damian, thanks for the response. Unfortunately, this doesn't seem to account for cases where a list item is long enough. I apologize for giving a poor example. – Coby Jun 28 '17 at 14:20
  • Sorry @ Damian, I should have given a better example. Suppose `lst = ['1234', '23456']` I was trying to get `['01234', '23456']` . The second number is not affected because it is sufficiently long. – Coby Jun 28 '17 at 14:52
  • @Coby aaaah now I get it, I will update the answer and let me know :) – developer_hatch Jun 28 '17 at 14:53
  • @Coby I think that's what you are looking at, and I did it this way to try to not modify your code so much. I hope it helps, don't forget voting and accepting if it was helpful :) – developer_hatch Jun 28 '17 at 14:56
2

You could use a list comprehension like this:

>>> ['0' * (5-len(x)) + x for x in lst]
['01234', '02345']

Or a list + map try:

>>> list(map(lambda x: '0' * (5-len(x)) + x, lst))
['01234', '02345']
blacksite
  • 12,086
  • 10
  • 64
  • 109
1

Ultimately, it was a combination of the answers that did the job.

lst = ['1234','2345']
newlst = []

for i in lst:
    i = i.zfill(5)
    newlst.append(i)

print(newlst)

I apologize if my example wasn't clear. Thank you to all who offered answers!

Coby
  • 136
  • 1
  • 2
  • 8
0

You can do this:

>>> lst = ['1234','2345']
>>> lst = ['0' * (5 - len(i)) + i for i in lst]
>>> print(lst)
['01234', '02345']
Dat Ha
  • 562
  • 1
  • 9
  • 16