Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

python - Identifying the data type of an input

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

, etc. I'm using python 3.2.3 and I know I could use type() to get the type of the data but in python all user inputs are taken as strings and I don't know how to determine whether the input is a string or Boolean or integer or float. Here is that part of the code:

user_var = input("Please enter something: ")
print("you entered " + user_var)
print(type(user_var))

which always returns str for string. Appreciate any help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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'>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...