Hi I am trying to print the data type of a user input and produce a table like following:
ABCDEFGH = String, 1.09 = float, 0 = int, true = bool
input() will always return a string. If you want to see if it is possible to be converted to an integer, you should do:
try:
int_user_var = int(user_var)
except ValueError:
pass # this is not an integer
You could write a function like this:
def try_convert(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
try:
return bool(s)
except ValueError:
return s
However, as mentioned in the other answers, using ast.literal_eval would be a more concise solution.