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

后端 未结 29 2861
醉话见心
醉话见心 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")))
    <class 'int'>
    

    string that is a float

    print(type(string_to_number("12.4")))
    <class 'float'>
    

    string that is a string

    print(type(string_to_number("hello")))
    <class 'str'>
    

    string that looks like a float

    print(type(string_to_number("hel.lo")))
    <class 'str'>
    
    0 讨论(0)
  • 2020-11-21 05:08

    I use this function for that

    import ast
    
    def parse_str(s):
       try:
          return ast.literal_eval(str(s))
       except:
          return
    

    It will convert the string to its type

    value = parse_str('1')  # Returns Integer
    value = parse_str('1.5')  # Returns Float
    
    0 讨论(0)
  • 2020-11-21 05:09
    >>> a = "545.2222"
    >>> float(a)
    545.22220000000004
    >>> int(float(a))
    545
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-21 05:10
    def num(s):
        """num(s)
        num(3),num(3.7)-->3
        num('3')-->3, num('3.7')-->3.7
        num('3,700')-->ValueError
        num('3a'),num('a3'),-->ValueError
        num('3e4') --> 30000.0
        """
        try:
            return int(s)
        except ValueError:
            try:
                return float(s)
            except ValueError:
                raise ValueError('argument is not a string of number')
    
    0 讨论(0)
提交回复
热议问题