plshelp plshelp - 27 days ago 9
Python Question

Detecting the type of data we have

I am importing a csv file into python. As expected, it creates lists with every value as a string, however I want to avoid this. Is there a way for python to detect that a value is actually an int even though it looks like this '24'?

Thank you.

Answer

You may want to write a function something like this to do the job. You can expand it to cover other data type.

def return_str_type(str):
    possible_type = [int, float]
    for dtype in possible_type:
        try:
            str = dtype(str)
            break   
        except:
            pass
    return type(str).__name__

print(return_str_type('4'))
print(return_str_type('4.3'))
print(return_str_type('s4'))

This will give OP

int
float
str

Though you will have to be careful with the order. e.g. int check should always be before float.

Comments