2016-03-05 65 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

相關問題