One way is to use the built-in eval()
method:
my_dataframe_list = ['df1', 'df2', 'df3']
my_dataframe_list = [eval(df) for df in my_dataframe_list]
Instead of the list comprehension, you can use map()
:
my_dataframe_list = ['df1', 'df2', 'df3']
my_dataframe_list = list(map(eval, my_dataframe_list))
But beware, the eval
method is dangerous; you should never use it on untrusted input. See this article for more details: Eval really is dangerous
Perhaps a more filtered list would be better:
my_dataframe_list = [eval(df) for df in my_dataframe_list if df.startswith('df') and df[2:].isdigit()]
But of course, the best thing you can do is to structure your existing code in a way that doesn't require the use of eval
.
This Stack Overflow post suggests the ast.literal_eval() method: Python: make eval safe
Of course, it would require you to install the ast
module, and the string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.