0

How do i take a list of a str tuple like this ['(1, 2, 3)', '(4, 5, 6)'] and I want run it through a for loop and get rid of string around it so first one will be (1, 2, 3) and second will be (4,5, 6).

Essentially, the '(1, 2, 3)' converted to (1, 2, 3) without importing any type of modules.

azro
  • 53,056
  • 7
  • 34
  • 70
  • _without importing any type of modules._ Why that restriction? Where does this data come from? – AMC Mar 29 '20 at 23:15
  • Does this answer your question? [How to get a data structure from inside a string (Python)](https://stackoverflow.com/questions/24838031/how-to-get-a-data-structure-from-inside-a-string-python) – AMC Mar 29 '20 at 23:15

1 Answers1

1

You can use literal_eval from the ast standard library:

from ast import literal_eval

values = ['(1, 2, 3)', '(4, 5, 6)']
result = [literal_eval(v) for v in values]
print(result)  # [(1, 2, 3), (4, 5, 6)]

A more classic way could be

result = []
for value in values:
    parsed_v = value.strip("()").replace(' ', '').split(",")
    result.append(tuple(int(p) for p in parsed_v))
print(result)  # [(1, 2, 3), (4, 5, 6)]


# expand it
result = []
for value in values:
    parsed_v = value.strip("()").replace(' ', '').split(",")
    tmp = list()
    for p in parsed_v:
        tmp.append(int(p))
    result.append(tuple(tmp))
print(result)  # [(1, 2, 3), (4, 5, 6)]
azro
  • 53,056
  • 7
  • 34
  • 70
  • Please do not ever suggest `eval`, especially not for something this trivial. See for example https://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval – Karl Knechtel Mar 29 '20 at 21:30
  • @KarlKnechtel I admit I'm not so familiar with the specificity of eval, could you tell me how is this dangerous here ? Or just use `literal_eval` everytime ? – azro Mar 29 '20 at 21:32
  • Thank you for this, but is there a way we can expand this line? result.append(tuple(int(p) for p in parsed_v)). I've not learned how to append with for loops on same line. Is there a way to expand that specific line with a for loop seperated from the append –  Mar 29 '20 at 22:02
  • @SportsPlanet i've have the loop, at the end – azro Mar 30 '20 at 08:31
  • @SportsPlanet You may now think about [accepting an answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) or comment one to get details ;) – azro Apr 01 '20 at 07:54