Home > database >  Convert str() to list() or tuple() without losing quotes
Convert str() to list() or tuple() without losing quotes

Time:10-12

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.

CodePudding user response:

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')

CodePudding user response:

  1. import ast library
  2. use ast.literal_eval("your_string") hope u find this usefull.
  • Related