String to int newbie question

Greg Ewing (using me at
Mon Mar 24 06:51:57 CET 2003

Luka Milkovic wrote:
> I have the following list: ['4312', '7599',
> '0724', '0003']. The things I need to do is to change the strings inside
> the list to integers and then write the list to a file

 > So, after the
> conversion of that list, what I want to have is: [4312, 7599, 0724, 0003]
> and NOT [4312, 7599, 724, 3].

Your problem seems to be concerned with output formatting.
You want the numbers to be written to the file as sequences
of characters with a specific number of digits for each number,

If you don't need to perform any arithmetic on the numbers,
you don't need to convert them to integers at all -- you
can leave them as strings. But you need to be careful how
you print them out -- if you just do

    print numbers

the default method of printing out lists of strings will
put quotes around the items. Try this instead:

    numbers = ['4312', '7599', '0724', '0003']
    print '[%s]' % ', '.join(numbers)

and you'll see that you get exactly what you asked for.

If you *do* need to do arithmetic on the numbers, then you'll
have to convert them to integers. But then you'll have to keep
track somehow of how many digits you want in the output, and
put leading zeroes in when you write out the results.

If you know the number of digits, e.g. if you know it's always
going to be 4, this is easy. The expression

    '%04d' % n

returns a string representation of the integer n with 4
digits, padded with leading zeroes. Try this:

    numbers = [4312, 4312, 724, 3]
    strings = []
    for n in numbers:
      strings.append('%04d' % n)

Now take a look at the value of strings and you'll see it
contains a list of strings in the right format. You can
then apply the above technique to get them printed without

Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand

More information about the Python-list mailing list