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

后端 未结 29 2789
醉话见心
醉话见心 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 04:51

    To typecast in python use the constructor funtions of the type, passing the string (or whatever value you are trying to cast) as a parameter.

    For example:

    >>>float("23.333")
       23.333
    

    Behind the scenes, python is calling the objects __float__ method, which should return a float representation of the parameter. This is especially powerful, as you can define your own types (using classes) with a __float__ method so that it can be casted into a float using float(myobject).

提交回复
热议问题