Zusman
Zusman

Reputation: 666

parse a string with brackets to arguments

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

Answers (2)

Chayan Bansal
Chayan Bansal

Reputation: 2085

import ast
print(list(ast.literal_eval(vars)))

Upvotes: 1

ForceBru
ForceBru

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

Related Questions