Here are simple test cases: -123., -123e0, -123, . will be considered reals or floats. Numbers which do not contain a decimal point or dot or an exponentiation part will be considered integers. Here is our function.
""" file dtypeval.py author Ernesto P. Adorio, PhD. UPDEPP at Clarkfield, Pampanga version 0.0.1 september 19, 2011 """ def dtypeval(s, numericfloat=False): """ Simple function to return the data type and value of a string. """ try: if numericfloat or ("." in s) or ("e" in s) or ("E" in s): f = float(s) return "float", f return "int", int(s) except: # print "[%s] is not a number!" % s return "str", s if __name__ == "__main__": teststring = ["-123.", "-123", "1e5", "1E5", ".001", "ABC"] for s in teststring: print s,"==>", dtypeval(s)Save the above to dtypeval.py and run from the command line python dtype.val. Here is the output:
-123. ==> ('float', -123.0) -123 ==> ('int', -123) 1e5 ==> ('float', 100000.0) 1E5 ==> ('float', 100000.0) .001 ==> ('float', 0.001) ABC ==> [ABC] is not a number! ('str', 'ABC')Note that numericfloat is set to true if the function is to return float always even if the input sting represents an integer.
No comments:
Post a Comment