1

I'd like to extend the code below so it can take double quotes. For example, the string '303,"Candy, Original",45,19' should return [303,"Candy, Original",45,19]. Please help. Thanks.

def parse(s):
    #If string can be parsed as integer, return integer
    try:
        num = int(s)
        return num
    except:
        pass
    #Else return string
    return s

data=[parse(x) for x in myString.split(",")]
James
  • 32,991
  • 4
  • 47
  • 70
Rik
  • 1,870
  • 3
  • 22
  • 35
  • 2
    This sounds like something the `csv` module should be able to handle – BallpointBen May 30 '19 at 01:01
  • 1
    Possible duplicate of [Python csv string to array](https://stackoverflow.com/questions/3305926/python-csv-string-to-array) – Sinan Ünür May 30 '19 at 01:01
  • 1
    `csv` can likely handle this situation, see [this question](https://stackoverflow.com/questions/56352450/formatting-csv-file-with-python/56361499#56361499) from earlier about how to handle quoted delimiters with that module. but we'd need to see a better [mcve] of your code & example inputs. – David Zemens May 30 '19 at 01:02
  • 1
    @DavidZemens : You introduced `" "` instead of the original `' '` – Sheldore May 30 '19 at 01:04
  • @Sheldore you're right! ¯\_(ツ)_/¯ – David Zemens May 30 '19 at 01:05

2 Answers2

3

The csv module handles quoted commas really well. You may want to try building a parser around that.

import csv
from io import StringIO

def to_numeric(x):
    try:
        return int(x)
    except ValueError:
        pass
    try:
        return float(x)
    except ValueError:
        pass
    return x

def parse_line(s):
    f = StringIO(s)
    f.seek(0)
    reader = csv.reader(f)
    out = next(reader)
    return [to_numeric(x) for x in out]

s = '303,"Candy, Original",45,19'
parse_line(s)
# returns:
[303, 'Candy, Original', 45, 19]
James
  • 32,991
  • 4
  • 47
  • 70
0

Solution using CSV:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06) 
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>> from io import StringIO
>>> csv_string = '303,"Candy, Original",45,19'
>>> csv_file = StringIO(csv_string)
>>> 
>>> reader = csv.reader(csv_file, delimiter=',')
>>> reader.__next__()
['303', 'Candy, Original', '45', '19']

You could then pass each value through an int or float coercion to get the native numerics if needed.

Jay
  • 2,861
  • 3
  • 29
  • 51