Alex Rivera | Logout

How to convert strings numbers to integers in a list?

Asked 2009-05-04T06:09:00.997
12

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.

Edit
Report

2 Answers

5

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])
answered 2009-05-04T06:18:20.660
5

Try this:

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

newList= list( convert( oldList ) )
answered 2009-05-04T10:40:37.503

Your Answer