Search code examples
arraysstringpython-2.5

Converting string values of a list to integer in python: ValueError: invalid literal?


Example list:

mylist=['7', '7_71_E Frastorf', '7', '7_71', '71', 'E Frastorf', '1208', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '40', '40', '41', '41', '41', '41', '41', '41', '41', '40', '37', '26', '', '', '', '', '', '', '']

I want to read part of the list elements as integer if the value is not ''.

I have treied:

mylist=[int(i)for i in mylist[6:] if i!=" "]

But it encounters following error:

ValueError: invalid literal for int() with base 10: ''

Could you please help me? Thanks, Shiuli


Solution

  • You needed to check for empty strings. This code checks for both space and empty.

    mylist=['7', '7_71_E Frastorf', '7', '7_71', '71', 'E Frastorf', '1208', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '41', '40', '40', '41', '41', '41', '41', '41', '41', '41', '40', '37', '26', '', '', '', '', '', '', ''] 
    
    mylist=[int(i) for i in mylist[6:] if i.strip() != '']
    
    print (mylist)