2013-07-02 33 views
0

所以,我有一個字符串列表python,我試圖找出哪些鍵是數字。 我試圖用list.[key].isdigit()只是到'0' 例如工作:字符串中的數字出現爲「不是數字」或錯誤 - Python

list = ['0', '0', '0', '0.450000000000000', '0', '0', '0', '0.550000000000000'] 

將只確定'0'是一個數字,但'0.45''0.55'都沒有。 我該如何解決這個問題?

非常感謝您

+0

看看這個鏈接 - http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Python –

回答

1

您可以使用異常處理和功能:

>>> def is_num(x): 
...  try : 
...   float(x) 
...   return True 
...  except ValueError: 
...   return False 
...  
>>> lis = ['0', '0', '0', '0.450000000000000', '0', '0', '0', '0.550000000000000'] 
>>> for x in lis: 
...  print is_num(x) 
...  
True 
True 
True 
True 
True 
True 
True 
True 
0

這科佩斯當空間和文字是喜憂參半: ''

import re 

def ok(val): 
    m = re.match('\s*\d+\.?\d*\s*', val) 
    if m and m.group(0) == val: 
     return True 
    return False 

list = ['0', '0.450000000000000', '0', '23x', ' 2.7 ', '2. 7', '1.2.3'] 

for val in list: 
    print ok(val), val 

# True 0 
# True 0.450000000000000 
# True 0 
# False 23x 
# True 2.7 
# False 2. 7 
# False 1.2.3 
0

您可以更換用零,檢查其數字或不假設你得到的只是浮在你的列表整數...

>>> a 
['0', '0.45'] 
>>> for each in a: 
...  repl = each.replace('.','0') 
...  if repl.isdigit(): 
...    print each 
... 
0 
0.45 
相關問題