首页 > 解决方案 > 自动将字符串转换为适当的类型

问题描述

我试图找到一个函数让python自动将字符串转换为“最简单”的类型。一些例子:

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 有一个名为type.convert的函数来执行此操作。在 python 中执行此操作的方法是什么?是否有现有功能或是否需要创建自定义功能?

标签: python

解决方案


如果失败,您可以使用ast.literal_eval, 并回退到不转换(返回原始字符串):

from ast import literal_eval

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

例子:

>>> simplest_type('54')
54
>>> simplest_type('6.34')
6.34
>>> simplest_type('False')
False
>>> simplest_type('text')
'text'

推荐阅读