Identifying the data type of an input

前端 未结 4 819
醉梦人生
醉梦人生 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 00:55

    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.

提交回复
热议问题