1

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!

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
  • 1
    Please update your question with the code you are using. – quamrana Sep 22 '22 at 12:55
  • you can use `eval` to evaluate those strings and convert them into tuples. do something like `[eval(i) for i in myList]` where `myList` is the one you posted. This will give as result a list of tuples `[('251', '122', '501'), ('288', '3', '506'), ('329', '5', '505'), ('390', '3', '501'), ('461', '140', '501')]` –  Sep 22 '22 at 12:56
  • 1
    Please be clear about what the output should look like – DarkKnight Sep 22 '22 at 13:01

2 Answers2

-1

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

rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
-1

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

vencaslac
  • 2,727
  • 1
  • 18
  • 29