Search code examples
pythonstringlistpython-3.xprepend

Prepend a string in Python


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


Solution

  • 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!