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(",")]
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]
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.