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']
2
  • What code have you written so far? Commented Jun 2, 2021 at 2:42
  • 1
    Does this answer your question? How to pad zeroes to a string? Commented Jun 2, 2021 at 6:37

5 Answers 5

3

Use zfill method:

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

In [2]: '12'.zfill(3)
Out[2]: '012'
Sign up to request clarification or add additional context in comments.

Comments

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']

Comments

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]

1 Comment

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.
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']

3 Comments

Thank you! This actually help me, I can understand this easily.
This approach doesn't scale very well for padding numbers of arbitrary length.
This is an insanely verbose answer, considering Python has builtin ways to do zero padding.
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.