1

What is the easiest way to convert a list of strings to a list of numbers so that those that look like integers converts to int and others to float?

Example:

list = ['1' , '2.2' , '3']

One way to convert is to define are they ints or floats:

list = [float(item) for item in list]

But in this example also obvious int would be converted to float as well.

One way could be to check variable type and convert case by case. Is there an easier way?


Edit:

A similar looking question How can I convert a string to either int or float with priority of int is a little hard to understand what the questions is, and accepted answer does not cover my case.

Another similar looking question How do I parse a string to float or int in Python is a basic question of how to convert to int or float and my question went a little further than that.

I'll ask again in other words: How to convert a string (or list of strings) to just to a number (or list of numbers), whatever type, retain its type whether int, float (or complex). Usually conversion is made from string to a certain type of number, usually to int or float. Is there an easy and obvious way to convert a string to a number of any kind?

PlasticDuck
  • 105
  • 1
  • 6
  • @Aran-Fey Hmm, I'm not convinced with that duplicate. Can you find a better one? If not, I'll reopen. This one needs literal_eval or an int/float inside a try/except. – cs95 May 27 '18 at 07:52
  • @coldspeed Did you see [this one](https://stackoverflow.com/questions/5608702/how-can-i-convert-a-string-to-either-int-or-float-with-priority-on-int)? (Did I add that after you posted your comment?) – Aran-Fey May 27 '18 at 07:53
  • @Aran-Fey Yes, you did. That's perf, ty. – cs95 May 27 '18 at 07:55

1 Answers1

2

Use the ast module.

Ex:

import ast
l = ['1' , '2.2' , '3']
print([ast.literal_eval(i) for i in l])

Output:

[1, 2.2, 3]
Rakesh
  • 81,458
  • 17
  • 76
  • 113