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

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

    This is a corrected version of https://stackoverflow.com/a/33017514/5973334

    This will try to parse a string and return either int or float depending on what the string represents. It might rise parsing exceptions or have some unexpected behaviour.

      def get_int_or_float(v):
            number_as_float = float(v)
            number_as_int = int(number_as_float)
            return number_as_int if number_as_float == number_as_int else 
            number_as_float
    

提交回复
热议问题