Determing the type of number stored as a string
Question: How do I tell whether a number, stored as a string, is an int or a float?

For example:

    
    
    def isint(x):
        if f(x):
            print 'this is an int'
        else:
            print 'this is a float'
    
    >>> x = '3'
    >>> isint(x)
    >>> this is an int
    >>> x = '3.14159'
    >>> isint(x)
    >>> this is a float
    

**What is the required`f(x)` function?**

One solution is to convert x to a float, find `r = x % 1`, and then determin
whether `r == 0`. But is there anything built into Python that does this for
me more neatly?


Answer: You can use
[`ast.literal_eval`](https://docs.python.org/2/library/ast.html#ast.literal_eval):

    
    
    >>> from ast import literal_eval
    >>> type(literal_eval('1.01'))
    <type 'float'>
    >>> type(literal_eval('1'))
    <type 'int'>
    >>> type(literal_eval('1+0j'))
    <type 'complex'>
    

If you want to do some sanity check as well, in case user might also pass a
non-numeric string:

    
    
    import numbers
    from ast import literal_eval
    
    def number_type(x):
        try:
            n = literal_eval(x)
            if isinstance(n, numbers.Number):
                print type(n).__name__
            else:
                print 'not a number' 
        except (ValueError, SyntaxError):
            print 'not a number'
    

