How to display leading zeros after splitting numbers in Python
Question: Is there any way I can display leading zeros after splitting numbers into
parts like first 3 digit and last 2 digit in Python 3.2? My script returns the
numbers with no leading zeros...

I have a csv file that looks like this:

    
    
    Name,Code
    blackberry,20001
    wineberry,02002
    rasberry,30000
    blueberry,03010
    

My desired output:

    
    
    Name,Code,Code1,Code2
    blackberry,20001,200,01
    wineberry,02002,020,02
    rasberry,30000,300,00   
    blueberry,03010,030,10
    

My script:

    
    
    import csv
    all = []
    with open('aaa.csv','r') as csvinput:
        with open('bbb.csv', 'w') as csvoutput:
            reader = csv.reader(csvinput,delimiter=',')
            writer = csv.writer(csvoutput,delimiter=",", lineterminator='\n')
            row = next(reader)
            row.append('Code1')
            row.append('Code2')
            all.append(row)
            for row in reader:
                row.append(row[1][0:2])
                row.append(row[1][-2:])
                all.append(row)
            writer.writerows(all)
            print(all)
    

Above script returns:

    
    
    Name,Code,Code1,Code2
    blackberry,20001,200,1
    wineberry,02002,20,2
    rasberry,30000,300,0    
    blueberry,03010,30,10
    


Answer: The `csv.writer` does not convert strings to numerical types, so it is not
causing the error you are seeing.

I expect that you are viewing your csv file in Excel, which converts strings
to numbers wherever it can. Look at your output in a text editor and you
should see that the leading zeros are really there.

Also, as others have pointed out your first slice should be `row[1][0:3]`.

