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?
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'> .
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With