Reputation: 666
I need to parse some strings into function variable lists.
I can have a simple string, such as vars = '3,5,1'
I parse it using args = [int(arg) if arg.isdigit() else arg for arg in vars.split(',')]
However I might get a string such as vars = [1, 2, 5, 4], 1, 5
And I want my result to be [[1,2,5,4],1,5]
How can I modify my parsing to support this case?
Upvotes: 0
Views: 266
Reputation: 44878
You can use the built-in ast
module:
import ast
result = ast.literal_eval(f'[{vars}]')
This will treat vars
as an ordinary list literal.
Upvotes: 1