Python multiple methods for determining whether a string is an alphanumeric of floating point number

  • 2020-12-09 00:55:37
  • OfStack

str is a string. s is a string

All characters are numbers or letters

All characters are letters

All characters are numbers

All characters are white space characters, t, n, r

Check that the string is a number/float method

float part


>> float('Nan')
nan
>> float('Nan')
nan
>> float('nan')
nan
>> float('INF')
inf
>> float('inf')
inf
>> float('-INF')
inf
>> float('-inf')
inf

Type 1: Simplest


def is_number(str):
  try:
    #  Because the use of float There are 1 An exception is 'NaN'
    if str=='NaN':
      return False
    float(str)
    return True
  except ValueError:
    return False
float Exceptions to the sample 
 >>> float('NaN')
 nan

Use the complex ()


def is_number(s):
  try:
    complex(s) # for int, long, float and complex
  except ValueError:
    return False
  return True

Comprehensive 1


def is_number(s):
  try:
    float(s) # for int, long and float
  except ValueError:
    try:
      complex(s) # for complex
    except ValueError:
      return False
  return True

Synthesis 2- is still not fully recognizable


def is_number(n):
  is_number = True
  try:
    num = float(n)
    #  check  "nan" 
    is_number = num == num  #  Or use  `math.isnan(num)`
  except ValueError:
    is_number = False
  return is_number
>>> is_number('Nan')  
False
>>> is_number('nan') 
False
>>> is_number('123') 
True
>>> is_number('-123') 
True
>>> is_number('-1.12')
True
>>> is_number('abc') 
False
>>> is_number('inf') 
True

The 2nd kind: can judge is integer only

Use the isnumeric ()


# str It must be uniconde model 
>>> str = u"345"
>>> str.isnumeric()True
http://www.tutorialspoint.com/python/string_isnumeric.htm
http://docs.python.org/2/howt...

Use the isdigit ()


https://docs.python.org/2/lib...
>>> str = "11"
>>> print str.isdigit()
True
>>> str = "3.14"
>>> print str.isdigit()
False
>>> str = "aaa"
>>> print str.isdigit()
False

Use the int ()


def is_int(str):
  try:
    int(str)
    return True
  except ValueError:
    return False

Type 3: Use regularization (safest approach)


import re
def is_number(num):
  pattern = re.compile(r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
  result = pattern.match(num)
  if result:
    return True
  else:
    return False
>>>: is_number('1')
True
>>>: is_number('111')
True
>>>: is_number('11.1')
True
>>>: is_number('-11.1')
True
>>>: is_number('inf')
False
>>>: is_number('-inf')
False

conclusion


Related articles: