Identifying the data type of an input
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Identifying The Data Type Of An Input
00:39 Answer 1 Score 4
01:10 Answer 2 Score 1
01:36 Accepted Answer Score 14
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/2219...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #types #userinput #python32
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Identifying The Data Type Of An Input
00:39 Answer 1 Score 4
01:10 Answer 2 Score 1
01:36 Accepted Answer Score 14
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/2219...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #python3x #types #userinput #python32
#avk47
ACCEPTED ANSWER
Score 14
from ast import literal_eval
def get_type(input_data):
try:
return type(literal_eval(input_data))
except (ValueError, SyntaxError):
# A string, so return str
return str
print(get_type("1")) # <class 'int'>
print(get_type("1.2354")) # <class 'float'>
print(get_type("True")) # <class 'bool'>
print(get_type("abcd")) # <class 'str'>
ANSWER 2
Score 4
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.
ANSWER 3
Score 1
Input will always return a string. You need to evaluate the string to get some Python value:
>>> type(eval(raw_input()))
23423
<type 'int'>
>>> type(eval(raw_input()))
"asdas"
<type 'str'>
>>> type(eval(raw_input()))
1.09
<type 'float'>
>>> type(eval(raw_input()))
True
<type 'bool'>
If you want safety (here user can execute arbitrary code), you should use ast.literal_eval:
>>> import ast
>>> type(ast.literal_eval(raw_input()))
342
<type 'int'>
>>> type(ast.literal_eval(raw_input()))
"asd"
<type 'str'>