0

So, I have a list of strings in python, and I am trying to find which keys are numbers. I am trying to use list.[key].isdigit() but it only works with '0' For instance:

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

will only determine that '0' is a digit, but '0.45' and '0.55' are not. How can I fix this problem?

Thank you very much

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Pototo
  • 691
  • 1
  • 12
  • 27

3 Answers3

1

You can use Exception handling and a function:

>>> 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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

This copes when spaces and text are mixed:

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
Michael Grazebrook
  • 5,361
  • 3
  • 16
  • 18
0

You can replace '.' with zeros and check if its numeric or not assuming you get only floats and ints in your list...

>>> a
['0', '0.45']
>>> for each in a:
...     repl = each.replace('.','0')
...     if repl.isdigit():
...             print each
...
0
0.45
user1050619
  • 19,822
  • 85
  • 237
  • 413