用双引号引起来时忽略逗号

时间:2019-05-30 00:55:47

标签: python string split

我想扩展下面的代码,以便可以使用双引号。例如,字符串'303,"Candy, Original",45,19'应该返回[303,"Candy, Original",45,19]。请帮忙。谢谢。

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(",")]

2 个答案:

答案 0 :(得分:3)

csv模块可以很好地处理引用的逗号。您可能想尝试围绕它构建一个解析器。

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]

答案 1 :(得分:0)

使用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']

然后,您可以根据需要通过intfloat强制传递每个值,以获取本机数字。