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


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!

Asked By: Preetam Kulkarni



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

Answered By: rv.kvetch

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]),

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

Answered By: vencaslac
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.