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

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

    Pass your string to this function:

    def string_to_number(str):
      if("." in str):
        try:
          res = float(str)
        except:
          res = str  
      elif(str.isdigit()):
        res = int(str)
      else:
        res = str
      return(res)
    

    It will return int, float or string depending on what was passed.

    string that is an int

    print(type(string_to_number("124")))
    
    

    string that is a float

    print(type(string_to_number("12.4")))
    
    

    string that is a string

    print(type(string_to_number("hello")))
    
    

    string that looks like a float

    print(type(string_to_number("hel.lo")))
    
    

提交回复
热议问题