How do I parse a string to a float or int?

后端 未结 29 2919
醉话见心
醉话见心 2020-11-21 04:43

In Python, how can I parse a numeric string like \"545.2222\" to its corresponding float value, 545.2222? Or parse the string \"31\" t

29条回答
  •  面向向阳花
    2020-11-21 05:04

    If you aren't averse to third-party modules, you could check out the fastnumbers module. It provides a function called fast_real that does exactly what this question is asking for and does it faster than a pure-Python implementation:

    >>> from fastnumbers import fast_real
    >>> fast_real("545.2222")
    545.2222
    >>> type(fast_real("545.2222"))
    float
    >>> fast_real("31")
    31
    >>> type(fast_real("31"))
    int
    

提交回复
热议问题