1

I'd like know if there is a quick way to accept data types as a user input directly so I can use it directly to cast type on other variables?
I am not looking for conditionals or for loops to check for all possible options. Thanks for the help in advance.
ex:

data_type = input('Enter a data type: str , bool, int or float: ')

user enters: str
I use datatype variable to change an integer to string type: datatype(234)

1 Answer 1

1

The usage of eval is not recommended, but that solves your question:

data_type = eval(input('Enter a data type: str , bool, int or float: '))

But we also have a safer method than eval. That is using the ast library:

import ast
data_type = ast.literal_eval(input('Enter a data type: str , bool, int or float: '))
Sign up to request clarification or add additional context in comments.

1 Comment

"eval" worked like a charm. Also thanks for the fair warning about the use of eval. I did some research and will be cautious. "ast.literal_eval" never works for me for some reason throwing ValueError for even the simplest expressions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.