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

后端 未结 29 3537
醉话见心
醉话见心 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:05

    This is another method which deserves to be mentioned here, ast.literal_eval:

    This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

    That is, a safe 'eval'

    >>> import ast
    >>> ast.literal_eval("545.2222")
    545.2222
    >>> ast.literal_eval("31")
    31
    

提交回复
热议问题