How to convert string of numbers enclosed in parenthesis to a tuple by removing the double inverted comas?

Viewed 41

I am new to python... I am using Python from Netlogo. I have an output that looks like this:

["('251','122','501')", "('288','3','506')", "('329','5','505')", "('390','3','501')", "('461','140','501')"]

I have been struggling to get rid of the double quotes... I have tried using replace(), and strip() but nothing works.

Thank you for the help!

2 Answers

I would use ast.literal_eval, or even just eval:

>>> import ast
>>> T = ["('251','122','501')", "('288','3','506')"]
>>> [ast.literal_eval(x) for x in T]
[('251', '122', '501'), ('288', '3', '506')]

See also: eval vs. ast.literal_eval

the issue here is that your original data structure is a list of strings, that happen to look like python tuples. the double quotes here are a way for python to tell you the datatype is a string.

there is no difference in type between this: ["string1", "string2", "string3"] and what you have

so what we have to do is write code to translate the strings into what we want. this should work:

def tupefy(some_string=None) -> tuple:
    return (int(some_string[1:-1].split()[0][1:-1]),
            int(some_string[1:-1].split()[1][1:-1]),
            int(some_string[1:-1].split()[2][1:-1]))

my_list = [tupefy(item) for item in my_list]

obviously this isn't perfect, it doesn't account for strings that are a different format or tuples that contain things other than numeric values, but I hope it's a good start for you

Related