V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fearme
V2EX  ›  Python

Python 字符串转数字的问题

  •  
  •   fearme · 2017-04-13 09:07:24 +08:00 via iPhone · 2848 次点击
    这是一个创建于 2573 天前的主题,其中的信息可能已经有所发展或是发生改变。
    只能用 try except 把 float ( str )包起来么
    6 条回复    2017-04-13 23:07:43 +08:00
    izhaohui
        1
    izhaohui  
       2017-04-13 09:14:36 +08:00 via Android
    调 str 的方法检查是否为数字喽
    ryd994
        2
    ryd994  
       2017-04-13 09:55:10 +08:00 via Android
    tryexcept 很正常的用法啊,为什么不用
    fearme
        3
    fearme  
    OP
       2017-04-13 09:56:59 +08:00
    @izhaohui 浮点数就不管用了
    boolean93
        4
    boolean93  
       2017-04-13 10:06:20 +08:00
    检查:数字、最多有一个小数点
    然后直接转就是喽
    wwqgtxx
        5
    wwqgtxx  
       2017-04-13 10:30:02 +08:00 via iPhone
    你可以用正则表达式检查一下嘛,虽然还不如 try except 性能高
    yucongo
        6
    yucongo  
       2017-04-13 23:07:43 +08:00   ❤️ 1
    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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1023 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 18:53 · PVG 02:53 · LAX 11:53 · JFK 14:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.