2

currently working with the below command:

python foo.py "['A,B,C,D','A,B,C','A,B','A']"

And I want to transform it into an actual string array:

A[0] = 'A,B,C,D'
A[1] = 'A,B,C' 
A[2] = 'A,B' 
A[3] = 'A' 

At the moment, I've been trying to use json.loads() and sys to read the string into an object or list.

However, it seems that the presence of the single-quotes cause the following error.

ValueError: No JSON object could be decoded

Yet, without the single-quotes, I end up the array:

B = ["A","B","C","D","A","B","C","A","B","A"]

How to get Python to ignore the inner commas while keeping track of the outer commas in order to produce the array of strings given in A shown above?

Wesam
  • 932
  • 3
  • 15
  • 27
Chloe Bennett
  • 901
  • 2
  • 10
  • 23

1 Answers1

1

You can use ast.literal_eval to...

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

>>> from ast import literal_eval
>>> literal_eval("['A,B,C,D','A,B,C','A,B','A']")
['A,B,C,D', 'A,B,C', 'A,B', 'A']
timgeb
  • 76,762
  • 20
  • 123
  • 145