如何检查字符串是否表示 Python 中的数值?
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
以上有效,但似乎很笨拙。
如果要测试的内容来自用户输入,则即使它表示 int
或浮点数
,它仍然是字符串。请参阅如何将输入读取为数字?用于转换输入,以及 要求用户输入,直到他们给出有效的响应以确保输入表示 int
或 float
(或其他要求),然后再继续。
网友回答:
其中,不仅丑陋且缓慢
我会对两者都提出异议。
正则表达式或其他字符串解析方法会更丑陋、更慢。
我不确定有什么比上面更快。它调用函数并返回。Try/Catch 不会带来太多开销,因为最常见的异常是在没有对堆栈帧进行广泛搜索的情况下捕获的。
问题是任何数字转换函数都有两种结果
C(例如)通过多种方式解决这个问题。Python清晰明了地阐述了它。
我认为您执行此操作的代码是完美的。
网友回答:
仅对于非负(无符号)整数,请使用:isdigit()
>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False
文档 : Python2, Python3isdigit()
对于 Python 2 Unicode 字符串:
。isnumeric()
网友回答:
博士最好的解决方案是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()
如果字符串不是数字,则例外块非常慢。但更重要的是,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”不受以下支持:
print(’科学记数法“1.000000e+50”不支持:’)
for f in funcs:
如果不是 f(scientific1):
print(’t -‘, f.name)
print(’科学记数法“1e50”不支持:’)
for f in funcs:
如果不是 f(scientific2):
print(’t -‘, f.name)
科学记数法“1.000000e+50”不受以下支持:
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()
模板简介:该模板名称为【如何检查字符串是否表示 Python 中的数值?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。