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.

4 Answers 4

41
changed_list = [int(f) if f.isdigit() else f for f in original_list]
4
  • 3
    An elegant one-liner. Behold the power of list comprehensions.
    – mkClark
    May 4, 2009 at 22:07
  • was thinking on similar lines
    – Nope
    Jul 28, 2009 at 1:31
  • good solution but what if list has float values also ['batting average', '306', 'ERA', '1710.5']
    – d.putto
    Jan 14, 2013 at 14:29
  • @d.putto added an answer to your question Apr 24, 2015 at 14:50
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])
1
  • Yep this is the best solution for the static case, while Alex's is best for the dynamic case.
    – Unknown
    May 4, 2009 at 6:20
5

Try this:

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

newList= list( convert( oldList ) )
0
a= ['batting average', '306', 'ERA', '1710.5']

[f if sum([c.isalpha() for c in f]) else float(f) for f in a ]

if your list contains float, string and int (as pointed about by @d.putto in the comment)

2
  • 1
    sum([c.isalpha() for c in f]) is quite a sub-optimal way to check "if any character in f is alphabetic" - try any(c.isalpha() for c in f) for improved readability and performance. Of course, both will fail if f equals for example '!' -- a string that's not a number but has no alphanumeric chars -- and also fail to convert e.g '1.7e3' -- a string that contains an alphanumeric char but would nevertheless be perfectly fine to pass as the argument to float ("exponential notation"). Apr 27, 2015 at 17:27
  • true. good point...posted it just to answer d.putto's specific contrived example. Should have put in more thought before posting my half baked answer ! Apr 27, 2015 at 22:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.