Python 字符串转数字的问题
只能用 try except 把 float ( str )包起来么
Python 字符串转数字的问题
调 str 的方法检查是否为数字喽
我无法理解你的问题
tryexcept 很正常的用法啊,为什么不用
检查:数字、最多有一个小数点
然后直接转就是喽
你可以用正则表达式检查一下嘛,虽然还不如 try except 性能高
Python 3.4:
a_str = '…‘
from contextlib import suppress
with suppress(Exception): a_str = float(a_str)
# a_str 可转 float 的话到这里就是 float 了, 不能转就还是 str
’ %s 可转 float :%s ’ % (a_str, isinstance(a_str, float))
E.g.:
from contextlib import suppress
a_str = ‘abc’
with suppress(Exception): a_str = float(a_str)
’ %s 可转 float :%s ’ % (a_str, isinstance(a_str, float)) $ False
a_str = ‘3.4’
with suppress(Exception): a_str = float(a_str)
’ %s 可转 float :%s ’ % (a_str, isinstance(a_str, float)) # True
a_str = ‘NaN’
with suppress(Exception): a_str = float(a_str)
’ %s 可转 float :%s ’ % (a_str, isinstance(a_str, float)) # True
a_str = ‘Nan’
with suppress(Exception): a_str = float(a_str)
’ %s 可转 float :%s ’ % (a_str, isinstance(a_str, float)) # True
a_str = ‘inf’
with suppress(Exception): a_str = float(a_str)
’ %s 可转 float :%s ’ % (a_str, isinstance(a_str, float)) # True

