Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert strings numbers to integers in a list?

I have a list say:

['batting average', '306', 'ERA', '1710']

How can I convert the intended numbers without touching the strings?

Thank you for the help.

like image 300
TIMBERings Avatar asked May 04 '09 06:05

TIMBERings


3 Answers

changed_list = [int(f) if f.isdigit() else f for f in original_list]
like image 61
Alex Martelli Avatar answered Oct 13 '22 15:10

Alex Martelli


The data looks like you would know in which positions the numbers are supposed to be. In this case it's probably better to explicitly convert the data at these positions instead of just converting anything that looks like a number:

ls = ['batting average', '306', 'ERA', '1710']
ls[1] = int(ls[1])
ls[3] = int(ls[3])
like image 33
sth Avatar answered Oct 13 '22 14:10

sth


Try this:

def convert( someList ):
    for item in someList:
        try:
            yield int(item)
        except ValueError:
            yield item

newList= list( convert( oldList ) )
like image 5
S.Lott Avatar answered Oct 13 '22 14:10

S.Lott