0

Which of the following is the best way of checking if a string could be represented as number?

a)

def is_number(s):
  try:
    float(s)
    return True
  except ValueError:
    return False

b)

Import re
check_regexp = re.compile(“^\d*\.?\d*$”)

c)

def isNumber(token):
  for char in token:
  if not char in string.digits: return false
    return True

d)

import re
check_replace = lambda x: x.replace(‘.’,’’,1).isdigit()
jterrace
  • 64,866
  • 22
  • 157
  • 202
RMK
  • 1,111
  • 4
  • 14
  • 33
  • 2
    This should help: http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-in-python – oznu Jan 30 '14 at 06:54

2 Answers2

2

All four versions do different things. As the first version is the only one that correctly handles negatives, I would prefer it in almost all cases. Even if the other versions were adjusted to return the same values as the first version, I would prefer the first version for clarity. However, if the input format needs to be more strict than what float accepts, perhaps not allowing inputs like '123e+4', then a correctly-written regex would probably be the simplest solution.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

You can this Python code, it will find string is number or float value.

def typeofvalue(text):
    try:
        int(text)
        return 'int'
    except ValueError:
        pass

    try:
        float(text)
        return 'float'
    except ValueError:
        pass

    return 'str'

typeofvalue("1773171")
Ashish Jain
  • 760
  • 1
  • 8
  • 23