Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # function to determine if a string can convert to an integer or float
- # and return a variable of the appropriate class and value
- # Mike Kerry - Jan 2021
- def getFloatIntStr(ip):
- # Return a float, int, or string)
- res = ip
- try:
- res = float(ip)
- return int(ip)
- except ValueError:
- return res
- mystring = ""
- myfloat = 0.0
- myint = 0
- for a in ["abc", "3.5", "8", "1.3.4", "01-06-1998", "12.5", "123"]:
- b = getFloatIntStr(a)
- if type(b) == str:
- mystring += (b + ",")
- elif type(b) == float:
- myfloat += b
- elif type(b) == int:
- myint += b
- # Results:
- # mystring: abc,1.3.4,01-06-1998,
- # myfloat total: 16.0
- # myint total: 131
- # Here is the same function with explanations
- def getFloatIntStr(ip):
- # Return a float, int, or string)
- # First we set a result variable "res" equal to the input string
- res = ip
- try:
- # Now we try converting the input string to a float.
- # If this fails, the "except" path will be taken and the original string is returned
- res = float(ip)
- # Execution only gets to here if the string was successfully converted to a float
- # This will be true if the string contained EITHER a float, OR an integer
- # res is now a variable of type float, containing the float representation of the input string
- # Now we attempt to convert the original string to an integer.
- # If the conversion to integer fails, then the input must have been a float,
- # and the exception path is taken, which returns the value with type = float
- # If the conversion to integer succceeds, the integer is returned here.
- return int(ip)
- except ValueError:
- # This except clause serves 2 purposes. It catches failed conversion to float, and failed conversion to integer
- # For the first failure, "res" contains the original string. For the 2nd failure, res contains the float value
- return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement