yucongo
2017-04-13 23:07:43 +08:00
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