Convert str() to list() or tuple() without losing quotes

Question:

Good afternoon!
I ran into a problem that on a "pure" python I can’t correctly convert a string of the form:

'("dbfd8379-f50c-4555-bc04-c138413cd27a", "2022-10-06 15:44:46.713", 1, "String for test1")'

To the list or tuple of the form:

["dbfd8379-f50c-4555-bc04-c138413cd27a", "2022-10-06 15:44:46.713", 1, "String for test1"]

("dbfd8379-f50c-4555-bc04-c138413cd27a", "2022-10-06 15:44:46.713", 1, "String for test1")

I’ve tried a lot of options, mostly with replace, strip and split. But all of them did not give the desired result.
I really ask for your help. Please help me to figure it out.

Answers:

Did you try with ast.literal_eval()?

text = '("dbfd8379-f50c-4555-bc04-c138413cd27a", "2022-10-06 15:44:46.713", 1, "String for test1")'

import ast
ast.literal_eval(text)

Output:

('dbfd8379-f50c-4555-bc04-c138413cd27a',
 '2022-10-06 15:44:46.713',
 1,
 'String for test1')
Answered By: Celius Stingher
  1. import ast library
  2. use ast.literal_eval("your_string")
    hope u find this usefull.
Answered By: Nouman Akram
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.