-2

I am trying to find a function to have python automatically convert a string to the "simplest" type. Some examples:

conversion_function("54") -> returns an int 54
conversion_function("6.34") -> returns a float 6.34
conversion_function("False") -> returns a boolean False
conversion_function("text") -> returns a str "text"

R has a function called type.convert that does this. What is the way to do this in python? Is there an existing function or does one need to create a custom one?

MartijnVanAttekum
  • 1,405
  • 12
  • 20

2 Answers2

4

You can use ast.literal_eval, and fall back to no conversion (returning the original string) if it fails:

from ast import literal_eval

def simplest_type(s):
    try:
        return literal_eval(s)
    except:
        return s

Examples:

>>> simplest_type('54')
54
>>> simplest_type('6.34')
6.34
>>> simplest_type('False')
False
>>> simplest_type('text')
'text'
kaya3
  • 47,440
  • 4
  • 68
  • 97
1

You can use ast.literal_eval.

import ast
a='[1,2,3]'
b='False'
c='1.2'

print(ast.literal_eval(a),ast.literal_eval(b),ast.literal_eval(c))

Note:

ast.literal_eval only works for valid python datatypes.

Ch3steR
  • 20,090
  • 4
  • 28
  • 58