Jun-22-2018, 04:25 PM
test if variable is Numeric?
test if variable is Numeric?
|
Jun-22-2018, 06:09 PM
A general function to determine type 'int', 'float' or 'string' might look something like:
def get_int_or_float(v): # NOTE: '1.0' will be identified as type 'int' try: number_as_float = float(v) number_as_int = int(number_as_float) if number_as_float == number_as_int: return number_as_int else : return number_as_float except: return v num1 = '1' num1 = get_int_or_float(num1) print("Input value '{}' is of type {}.".format(num1, type(num1))) num1 = '1a' num1 = get_int_or_float(num1) print("Input value '{}' is of type {}.".format(num1, type(num1))) num1 = '1.1' num1 = get_int_or_float(num1) print("Input value '{}' is of type {}.".format(num1, type(num1))) num1 = 1 num1 = get_int_or_float(num1) print("Input value '{}' is of type {}.".format(num1, type(num1))) num1 = 1.1 num1 = get_int_or_float(num1) print("Input value '{}' is of type {}.".format(num1, type(num1))) Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
This is my take - form a production code (I use it to load
ini files - thus the name)def convert_config_value(value): for numeric_type in (int, float): try: converted_value = numeric_type(value) return converted_value except ValueError: pass return value Ooops, seems like I misread the question (I saw the post by @ljmetzger - and misinterpreted the OP). Of course, this a method for string conversion.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
|
|
Users browsing this thread: 2 Guest(s)