Python中的字符串转换

时间:2017-09-06 04:50:35

标签: python regex string escaping

如何像这样转换字符串,我需要将两个双引号转换为\"。

"Alexandra ""Alex""",Menendez,alex.menendez@gmail.com,Miami,1
["Alexandra \"Alex\"", "Menendez", "alex.menendez@gmail.com", "Miami", "1"]

返回应该是一个列表,以及我遇到问题的地方。这就是我想出来的

def parseCsv(sentence):
    result = []
    new_result = []
    sent_1 = list(sentence)
    new_str = ""
    new_w = ""

    for s in sent_1:
        if s != ',':
            new_str += " ".join(s)
        elif new_str:
            result.append(new_str)
            new_str = ""
    result.append(new_str)

    for i, w in enumerate(result):
        if w.startswith("\"") or w.endswith("\""):
            new_w += result[i]
            if new_w.startswith("\"") and new_w.endswith("\""):
                x = new_w.replace('""', r'\"')
                new_result.append(x)
                new_w = ""
        else:
            new_result.append(w)
    return new_result

我得到的是

['"Alexandra \\"Alex\\""', 'Menendez', 'alex.menendez@gmail.com', 'Miami', '1']

2 个答案:

答案 0 :(得分:4)

您无需做任何事情。 csv模块将正确加载您的数据:

import csv
from io import StringIO

infile = StringIO('"Alexandra ""Alex""",Menendez,alex.menendez@gmail.com,Miami,1')
reader = csv.reader(infile)
for row in reader:
    print(row)

# output:
# ['Alexandra "Alex"', 'Menendez', 'alex.menendez@gmail.com', 'Miami', '1']

答案 1 :(得分:0)

比如说,在将句子转换为列表并迭代每个元素之后,请执行以下regsub

考虑' a'是列表中的元素

a= "\"Alexadra \"\"Alex\"\"\""

print(a)

y=re.sub('\"{2}', '\\\"', a)

y will replace your double quotes with \" i.e a slash with single quote

If only single quote is required try

z=re.sub('\"{2}', '\"', a)