2016-03-05 70 views
4

我正在使用它来检查一个变量是否是数字,我也想检查它是否是一个浮点数。如何检查一个字符串是否代表浮点数

if(width.isnumeric() == 1) 
+1

你想要'3'和'3.5'进入同一张支票吗? – zondo

+0

'isinstance(width,type(1.0))'在Python 2.7中工作 –

+1

[检查数字是int还是浮点数]可能的重复(http://stackoverflow.com/questions/4541155/check-if-a-number -is-int-or-float) – JGreenwell

回答

6
def is_float(string): 
    try: 
    return float(string) and '.' in string # True if string is a number contains a dot 
    except ValueError: # String is not a number 
    return False 

输出:

>> is_float('string') 
>> False 
>> is_float('2') 
>> False 
>> is_float('2.0') 
>> True 
>> is_float('2.5') 
>> True 
+0

不太好,看到https://stackoverflow.com/questions/379906/parse-string-to-float-or-int –

14

最简单的方法是将字符串转换为浮点与float()

>>> float('42.666') 
42.666 

如果它不能被转换为一个浮,你会得到一个ValueError

>>> float('Not a float') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: could not convert string to float: 'Not a float' 

使用try/except块通常被认为处理的最佳方式:

try: 
    width = float(width) 
except ValueError: 
    print('Width is not a number') 

注意你也可以使用is_integer()float()来检查它是否是一个整数:

>>> float('42.666').is_integer() 
False 
>>> float('42').is_integer() 
True 
+0

添加一个尝试/除...但是这是最正确的答案伊莫:) :) –

+1

使用'is_integer()'将浮点数和int进行区分是一种很好的方式。 – mhawke

相关问题