0

I have a tuple like string line like:

("a",10,4,"abc")

I would like to parse it to contain each item in a string list:

ans = [a, 10, 4, abc]

In the example, I achieve easily it splitting the string line with comma.

However, a string item in the string line might have commas and double quotations, like

("abc",10,-4,"abc"","d,ef")

I would like get the string list.

ans = [abc, 10, -4, abc", d,ef]

Does anyone have a good idea to achieve it with Python?

Atsushi Sakai
  • 619
  • 7
  • 16
  • 2
    I don't understand the question. What is `ans = [a, 10, 4, abc]`? Specifically, what is the `a` and `abc`? – quamrana Mar 07 '19 at 12:03
  • 2
    Double quotes in a string must be escaped if the string is also enclosed by double quotes, i.e. `"abc\""`. Likewise for single quotes. – meowgoesthedog Mar 07 '19 at 12:06
  • Please update your question with the code you have tried. You seem to describe something to do with splitting. Please show that code. – quamrana Mar 07 '19 at 12:20

1 Answers1

1

If the string is encapsulate with double qoutes & you are using a " in it. so need to use the escape character \ to represent that it is a character.

Try this code !

import ast

print(list(ast.literal_eval('("abc",10,-4,"abc\\"","d,ef")')))

Output :

['abc', 10, -4, 'abc"', 'd,ef'] 
Usman
  • 2,023
  • 11
  • 25