DataWise
DataWise

Reputation: 13

How can I convert a user's string input such as 'int' or 'float' to types str and float?

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)

Upvotes: 1

Views: 309

Answers (1)

Joshua Varghese
Joshua Varghese

Reputation: 5202

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: '))

Upvotes: 1

Related Questions