Python数据类型发现

时间:2018-08-30 18:19:32

标签: python types

我有一个接收str的函数,该函数可以表示以下任何一个:

float <-- eg: '1.5', '1.0'
int <-- eg: '123','0'
datetime.date <-- eg: if so, it'll always be in this format '30-AUG-18'
str <-- eg: "value1", "01", "02"
NoneType <-- eg: None

如何优雅地发现输入并将其转换为适当的类型?

2 个答案:

答案 0 :(得分:0)

您可以使用python的类型转换来实现此目的:

float('2.3')
int('2')
datetime.strptime('2018-02-02', '%Y-%m-%d')

答案 1 :(得分:0)

看看ast.literal_eval

from ast import literal_eval
from datetime import datetime

def dataType(s):
    s = s.strip()
    try:
        t = literal_eval(s)
    except ValueError:
        try:
            return 'datetime.date', datetime.strptime(s.upper(), '%d-%b-%y')
        except ValueError:
            return 'str', s
    except SyntaxError:
        return 'str', s
    else:
        return type(t).__name__, t

for s in ['1.5', '1.0', '123', '0', '30-AUG-18', 'value1', '01', '02', 'None']:
    type_name, value = dataType(s)
    print(type_name, str(value))

输出:

float 1.5
float 1.0
int 123
int 0
datetime.date 2018-08-30 00:00:00
str value1
str 01
str 02
NoneType None