0

I am trying to create a list from a string delimited by commas, but there are a set of values within the string contained within quotes that also include commas. I want to create a list that ignores the commas within the quotes. I have a few hundred text documents in this format. This is (one of many of) the string:

str = ('1ATB,"300,2986,4151,3719,3488,3027,3123,3348,3530", ,2019-11-27 12:45:11.000,000-286428,Paint Powder,1ATB,')

The resulting list I am trying to get is:

['1ATB', '"300, 2986, 4151, 3719, 3488, 3027, 3123, 3348, 3530"', ' ', '2019-11-27 12:45:11.000', '000-286428', 'Paint Powder', '1ATB', '']

My first attempt of:

str=('1ATB,"300,2986,4151,3719,3488,3027,3123,3348,3530", ,2019-11-27 12:45:11.000,000-286428,Paint Powder,1ATB,')
list1 = str.split(",")

Yields the result of:

['1ATB', '"300', '2986', '4151', '3719', '3488', '3027', '3123', '3348', '3530"', ' ', '2019-11-27 12:45:11.000', '000-286428', 'Paint Powder', '1ATB', '']

I appreciate any advice for this.

Durren
  • 3
  • 2

1 Answers1

0

Perhaps the CSV module can help.

>>> s = ('1ATB,"300,2986,4151,3719,3488,3027,3123,3348,3530", ,2019-11-27 12:45:11.000,000-286428,Paint Powder,1ATB,')
>>> print(s)
1ATB,"300,2986,4151,3719,3488,3027,3123,3348,3530", ,2019-11-27 12:45:11.000,000-286428,Paint Powder,1ATB,
>>> from io import StringIO
>>> import csv
>>> f = StringIO(s)
>>> reader = csv.reader(f)
>>> row = next(reader)
>>> row
['1ATB', '300,2986,4151,3719,3488,3027,3123,3348,3530', ' ', '2019-11-27 12:45:11.000', '000-286428', 'Paint Powder', '1ATB', '']
>>> row2 = [f'"{col}"' if ',' in col else col for col in row]
>>> row2
['1ATB', '"300,2986,4151,3719,3488,3027,3123,3348,3530"', ' ', '2019-11-27 12:45:11.000', '000-286428', 'Paint Powder', '1ATB', '']
>>>
Justin Ezequiel
  • 5,254
  • 2
  • 11
  • 14