imhans4305
imhans4305

Reputation: 697

List of tuples in String format to List of tuples Conversion

I have a list of tuples where tuple is in string format

data_list = ["('https://www.test.org/', 'testing', 'test1', 'test1')", "('https://testing2.com/', 'testing', 'test2', 'test2')"]

To convert this to list of tuples I am using the following code

for val in data_list:
    valx = ast.literal_eval(val)

But some time I will have the list of tuples with Undefined parameter like below.

["('https://www.test.org/', 'testing', Undefined, Undefined)", "('https://testing.com/', 'testing', Undefined, Undefined)"]

In this case using the above code will give the following error

flask    |     raise ValueError(f'malformed node or string: {node!r}')
flask    | ValueError: malformed node or string: <_ast.Name object at 0x7fab4d78ab80>

I am not sure how to handle this error. In the place of Undefined, a null string will be enough.

Upvotes: 0

Views: 38

Answers (1)

tturbo
tturbo

Reputation: 1166

How about replace it with None? (In my example with eval instead of ast.literal_eval:

data_list = ["('https://www.test.org/', 'testing', Undefined, 'test1')", "('https://testing2.com/', 'testing', 'test2', 'test2')"]

for val in data_list:
    val = val.replace('Undefined', 'None')
    valx = eval(val)
    print(valx)

You may want to use regex to differ between Undefined und 'Undefined' (string)

Upvotes: 1

Related Questions