Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine the type of a value which is represented as string in python

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]) <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?

like image 656
IezyBoy Avatar asked Jan 20 '10 16:01

IezyBoy


People also ask

How do I find the data type of a string in Python?

Check if Variable is a String with type() The built-in type() function can be used to return the data type of an object. For example, we'll be expecting the returned value of this function to be <class 'str'> .

How do you check if a value is a string in Python?

Method #1 : Using isinstance(x, str) This method can be used to test whether any variable is a particular datatype. By giving the second argument as “str”, we can check if the variable we pass is a string or not.

How do you check if a variable is a string?

Use the typeof operator to check if a variable is a string, e.g. if (typeof variable === 'string') . If the typeof operator returns "string" , then the variable is a string. In all other cases the variable isn't a string. Copied!


1 Answers

You could do something like this:

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'>

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.

like image 129
Nadia Alramli Avatar answered Oct 30 '22 13:10

Nadia Alramli