TL;DR最佳解决方案是s.replace('.','',1).isdigit()
我做了一些比较不同方法的基准测试
def is_number_tryexcept(s):
""" Returns True if string is a number. """
try:
float(s)
return True
except ValueError:
return False
import re
def is_number_regex(s):
""" Returns True if 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 if string is a number. """
return s.replace('.','',1).isdigit()
如果字符串不是数字,则except块非常慢。但更重要的是,try-except方法是正确处理科学符号的唯一方法。
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__)
以下项不支持浮点符号“.1234”:
is_number_regex编号科学1='1.000000e+50'科学2=“1e50”print('不支持科学符号“1.0000000e+50”:')对于函数中的f:如果不是f(科学1):打印('\t-',f.name)print('不支持科学符号“1e50”:')对于函数中的f:如果不是f(科学2):打印('\t-',f.name)
以下各项不支持科学符号“1.0000000e+50”:
is_number_regex编号is_number_repl_isdigit编号以下各项不支持科学符号“1e50”:is_number_regex编号is_number_repl_isdigit编号
编辑:基准结果
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 if string is a number. """
try:
float(s)
return True
except ValueError:
return False
def is_number_regex(s):
""" Returns True if 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 if string is a number. """
if comp.match(s) is None:
return s.isdigit()
return True
def is_number_repl_isdigit(s):
""" Returns True if string is a number. """
return s.replace('.','',1).isdigit()