Advertisement
acclivity

Convert string to Int, Float or String as appropriate

Feb 27th, 2021 (edited)
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. # function to determine if a string can convert to an integer or float
  2. # and return a variable of the appropriate class and value
  3.  
  4. # Mike Kerry - Jan 2021
  5.  
  6. def getFloatIntStr(ip):
  7.     # Return a float, int, or string)
  8.     res = ip
  9.     try:
  10.         res = float(ip)
  11.         return int(ip)
  12.     except ValueError:
  13.         return res
  14.  
  15. mystring = ""
  16. myfloat = 0.0
  17. myint = 0
  18.  
  19. for a in ["abc", "3.5", "8", "1.3.4", "01-06-1998", "12.5", "123"]:
  20.     b = getFloatIntStr(a)
  21.     if type(b) == str:
  22.         mystring += (b + ",")
  23.     elif type(b) == float:
  24.         myfloat += b
  25.     elif type(b) == int:
  26.         myint += b
  27.  
  28. # Results:
  29. # mystring: abc,1.3.4,01-06-1998,
  30. # myfloat total: 16.0
  31. # myint total: 131
  32.  
  33. # Here is the same function with explanations
  34. def getFloatIntStr(ip):
  35.  
  36.     # Return a float, int, or string)
  37.     # First we set a result variable "res" equal to the input string
  38.     res = ip
  39.     try:
  40.         # Now we try converting the input string to a float.
  41.         # If this fails, the "except" path will be taken and the original string is returned
  42.         res = float(ip)
  43.  
  44.         # Execution only gets to here if the string was successfully converted to a float
  45.         # This will be true if the string contained EITHER a float, OR an integer
  46.         # res is now a variable of type float, containing the float representation of the input string
  47.  
  48.         # Now we attempt to convert the original string to an integer.
  49.         # If the conversion to integer fails, then the input must have been a float,
  50.         # and the exception path is taken, which returns the value with type = float
  51.         # If the conversion to integer succceeds, the integer is returned here.
  52.         return int(ip)
  53.  
  54.     except ValueError:
  55.         # This except clause serves 2 purposes. It catches failed conversion to float, and failed conversion to integer
  56.         # For the first failure, "res" contains the original string. For the 2nd failure, res contains the float value
  57.         return res
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement