确定存储为字符串的数字类型

时间:2014-07-03 19:43:53

标签: python

如何判断存储为字符串的数字是int还是float?

例如:

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

所需的f(x)功能是什么?

一种解决方案是将x转换为浮点数,找到r = x % 1,然后确定是否r == 0。但是,Python中是否有任何内容可以为我更加整洁地做到这一点?

4 个答案:

答案 0 :(得分:5)

您可以使用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'>

如果您还想进行一些健全性检查,以防用户也可能传递非数字字符串:

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'

答案 1 :(得分:1)

您可以使用try/except block查看字符串编号是否可以转换为整数:

def isint(x):
    try:
        int(x)
        print 'this is an int'
    except ValueError:
        print 'this is an float'

参见下面的演示:

>>> def isint(x):
...     try:
...         int(x)
...         print 'this is an int'
...     except ValueError:
...         print 'this is an float'
...
>>> isint('123')
this is an int
>>> isint('123.0')
this is an float
>>>

如果您想防止用户输入非数字字符串,您可以再添加一个级别的错误处理:

def isint(x):
    try:
        int(x)
        print 'this is an int'
    except ValueError:
        try:
            float(x)
            print 'this is an float'
        except ValueError:
            print 'this is not a number'

答案 2 :(得分:0)

>>> def isint(x):
    return '.' not in x

>>> isint("3.14")
False
>>> isint("3")
True

答案 3 :(得分:0)

我认为最简单的变体是使用eval:

eval("1.7") => 1.7 => type=float
eval("1") => 1 => type=int
eval("143274892053294870824") => 143274892053294870824 => type=long
isint = lambda x: isinstance(eval(x), int)

不要将不受信任的代码传递给此函数;)