Search code examples
pythonlistloopsiterationinfinite-loop

Add trailing "0" to have each part of the list have 5 chracters


I am trying to iterate over a list (called lista) in order to print out a new list with each part of it having exactly 5 characters.

lista = ['123', '2', '34322', '332']


while True:
        for i in lista:
            if len(lista[lista.index(i)]) < 5:
                lista[lista.index(i)] += '0'
        else:
            break
print(lista)

My output however, is:

['1230', '20', '34322', '3320']

The only way I can get the right number of characters is when I create an infinite loop by removing the "break" statement.

Any help is greatly appreciated.


Solution

  • I assume you want the output to be in the form of: ['00123', '00002', '34322', '00332'] If this is true, then the below piece of code is your solution!

    lista = ['123', '2', '34322', '332']
    zero="0"
    finalList=[]
    for i in lista:
        remainingChar=0
        if(len(i)<5):
            remainingChar=5-len(i)
            finalList.append((remainingChar*zero)+i)
        else:
            finalList.append(i)
    print(finalList)