'Python - String.split() using delimiter ',', but there is price in string also using comma in thousand

I am trying to use Python to parse a CSV file. I have a string like this:

"11/11/14","Buy","1,900","$10.40","-$19,760.00"

I want to parse it to into list like this

  • element 1 -> "11/11/14"
  • element 2 -> "Buy"
  • element 3 -> "1,900"
  • element 4 -> "$10.40"
  • element 5 -> "-$19,760.00"

However, since there is comma delimiter in thousands number, the parse result is

  • element 1 -> "11/11/14"
  • element 2 -> "Buy"
  • element 3 -> "1
  • element 4 -> 900"
  • element 5 -> "$10.40"
  • element 6 -> "-$19
  • element 7 -> 760.00"

Here is my code:

data = line.split(',')


Solution 1:[1]

You might want to look at the csv module in the python standard library. This will automatically take care of quoted strings within the elements of the CSV. For example:

with open('eggs.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='\"')
    for row in spamreader:
        print(', '.join(row))

This will load in a file and read it line by line, then print out the contents of each element separated by a comma. The result should match what you need.

Solution 2:[2]

use,

data = line.strip('"').split('","')

There's no "Quote" in prices.

Solution 3:[3]

Split on "\",\"" instead, then assuming there are no spaces in your delimiter it'll work, otherwise use regex to allow spaces.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chenrui
Solution 2
Solution 3