Identifying the data type of an input

前端 未结 4 815
醉梦人生
醉梦人生 2020-12-02 00:36

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

4条回答
  •  [愿得一人]
    2020-12-02 01:00

    Input will always return a string. You need to evaluate the string to get some Python value:

    >>> type(eval(raw_input()))
    23423
    
    >>> type(eval(raw_input()))
    "asdas"
    
    >>> type(eval(raw_input()))
    1.09
    
    >>> type(eval(raw_input()))
    True
    
    

    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(ast.literal_eval(raw_input()))
    "asd"
    
    

提交回复
热议问题