确定在python中表示为字符串的值的类型 [英] determine the type of a value which is represented as string in python

查看:157
本文介绍了确定在python中表示为字符串的值的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在python中使用csv解析器读取逗号分隔的文件或字符串时,所有项目都表示为字符串。请参阅以下示例。

When I read a comma seperated file or string with the csv parser in python all items are represented as a string. see example below.

import csv
a = "1,2,3,4,5"
r = csv.reader([a])
for row in r:
    d = row

d
['1 ','2','3','4','5']
type(d [0])

d ['1', '2', '3', '4', '5'] type(d[0]) <type 'str'>

我想为每个值确定它是一个字符串,浮点数,整数还是日期。

I want to determine for each value if it is a string, float, integer or date. How can I do this in python?

推荐答案

你可以这样做:

from datetime import datetime

tests = [
    # (Type, Test)
    (int, int),
    (float, float),
    (datetime, lambda value: datetime.strptime(value, "%Y/%m/%d"))
]

def getType(value):
     for typ, test in tests:
         try:
             test(value)
             return typ
         except ValueError:
             continue
     # No match
     return str

>>> getType('2010/1/12')
<type 'datetime.datetime'>
>>> getType('2010.2')
<type 'float'>
>>> getType('2010')
<type 'int'>
>>> getType('2013test')
<type 'str'>

关键是在测试顺序中,例如int测试应该在float测试之前。对于日期,您可以为要支持的格式添加更多测试,但显然您无法涵盖所有​​可能的情况。

The key is in the tests order, for example the int test should be before the float test. And for dates you can add more tests for formats you want to support, but obviously you can't cover all possible cases.

这篇关于确定在python中表示为字符串的值的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆