Python 字符串转数字的问题

2017-04-13 09:07:24 +08:00
 fearme
只能用 try except 把 float ( str )包起来么
2856 次点击
所在节点    Python
6 条回复
izhaohui
2017-04-13 09:14:36 +08:00
调 str 的方法检查是否为数字喽
ryd994
2017-04-13 09:55:10 +08:00
tryexcept 很正常的用法啊,为什么不用
fearme
2017-04-13 09:56:59 +08:00
@izhaohui 浮点数就不管用了
boolean93
2017-04-13 10:06:20 +08:00
检查:数字、最多有一个小数点
然后直接转就是喽
wwqgtxx
2017-04-13 10:30:02 +08:00
你可以用正则表达式检查一下嘛,虽然还不如 try except 性能高
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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/354515

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX