[Tutor] casting string to integer in a list of lists

wesley chun wescpy at gmail.com
Thu Jan 8 23:21:39 CET 2009


>> LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'],
>>        :
>> Now I want to cast the second and third "columns" from string to integer,
>> like this
>>
>> LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'],
>>        :
>> Is there any elegant way to do this? I can't assume that all lines will
>> have the same number of elements.

the easiest way to do it is using int(), as in the below.


> for lstA in LoL:
>     try:
>         lstA[1] = int(lstA[1])
>     except:
>         pass
>     try:
>         lstA[2] = int(lstA[2])
>     except:
>         pass

it's definitely a *good* idea to check and make sure the numbers are
legit, meaning that int() won't throw an exception, but it is a *bad*
idea to have any code anywhere that looks like:

except:
    pass

try not to code these 2 lines in anything that you do because it will
come back to haunt you when something is not working right but you
can't find any errors. that's because this code masks and throws away
everything!!

if you are guaranteed that the strings all contain valid integers,
then you don't have to worry about problems calling int().

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list