推荐学习书目
› 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 · Apr 13, 2017 via iPhone · 3831 views
    This topic created in 3452 days ago, the information mentioned may be changed or developed.
    只能用 try except 把 float ( str )包起来么
    6 replies  •  2017-04-13 23:07:43 +08:00
    izhaohui
        1
    izhaohui  
       Apr 13, 2017 via Android
    调 str 的方法检查是否为数字喽
    ryd994
        2
    ryd994  
       Apr 13, 2017 via Android
    tryexcept 很正常的用法啊,为什么不用
    fearme
        3
    fearme  
    OP
       Apr 13, 2017
    @izhaohui 浮点数就不管用了
    boolean93
        4
    boolean93  
       Apr 13, 2017
    检查:数字、最多有一个小数点
    然后直接转就是喽
    wwqgtxx
        5
    wwqgtxx  
       Apr 13, 2017 via iPhone
    你可以用正则表达式检查一下嘛,虽然还不如 try except 性能高
    yucongo
        6
    yucongo  
       Apr 13, 2017   ❤️ 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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2405 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 05:00 · PVG 13:00 · LAX 22:00 · JFK 01:00
    ♥ Do have faith in what you're doing.