views:

834

answers:

4

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.

+38  A: 
changed_list = [int(f) if f.isdigit() else f for f in original_list]
Alex Martelli
An elegant one-liner. Behold the power of list comprehensions.
mkClark
was thinking on similar lines
Casey
+5  A: 

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])
sth
Yep this is the best solution for the static case, while Alex's is best for the dynamic case.
Unknown
+3  A: 

Try this:

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

newList= list( convert( oldList ) )
S.Lott
A: 

Thanks for the help guys... I ended up using Alex's code

TIMBERings
Then mark it as the answer.
projecktzero