python - Comment vérifier si une chaîne est un nombre (float)

Mots clés : pythoncastingfloating-pointtype-conversionpython

meilleur 4 Réponses python - Comment vérifier si une chaîne est un nombre (float)

vote vote

92

>>> a = "03523" >>> a.isdigit() True >>> b = "963spam" >>> b.isdigit() False 
vote vote

82

def is_number_tryexcept(s):     """ Returns True is string is a number. """     try:         float(s)         return True     except ValueError:         return False  import re     def is_number_regex(s):     """ Returns True is string is a number. """     if re.match("^\d+?\.\d+?$", s) is None:         return s.isdigit()     return True   def is_number_repl_isdigit(s):     """ Returns True is string is a number. """     return s.replace('.','',1).isdigit() 
funcs = [           is_number_tryexcept,            is_number_regex,           is_number_repl_isdigit           ]  a_float = '.1234'  print('Float notation ".1234" is not supported by:') for f in funcs:     if not f(a_float):         print('\t -', f.__name__) 
scientific1 = '1.000000e+50' scientific2 = '1e50'   print('Scientific notation "1.000000e+50" is not supported by:') for f in funcs:     if not f(scientific1):         print('\t -', f.__name__)     print('Scientific notation "1e50" is not supported by:') for f in funcs:     if not f(scientific2):         print('\t -', f.__name__) 
import timeit  test_cases = ['1.12345', '1.12.345', 'abc12345', '12345'] times_n = {f.__name__:[] for f in funcs}  for t in test_cases:     for f in funcs:         f = f.__name__         times_n[f].append(min(timeit.Timer('%s(t)' %f,                        'from __main__ import %s, t' %f)                               .repeat(repeat=3, number=1000000))) 
from re import match as re_match from re import compile as re_compile  def is_number_tryexcept(s):     """ Returns True is string is a number. """     try:         float(s)         return True     except ValueError:         return False  def is_number_regex(s):     """ Returns True is string is a number. """     if re_match("^\d+?\.\d+?$", s) is None:         return s.isdigit()     return True   comp = re_compile("^\d+?\.\d+?$")      def compiled_regex(s):     """ Returns True is string is a number. """     if comp.match(s) is None:         return s.isdigit()     return True   def is_number_repl_isdigit(s):     """ Returns True is string is a number. """     return s.replace('.','',1).isdigit() 
vote vote

72

>>> float('NaN') nan 
vote vote

64

'3.14'.replace('.','',1).isdigit() 
'3.14.5'.replace('.','',1).isdigit() 

Questions similaires