Reputation: 194
How can I transform the string like this, I need to convert two double quotes to a \".
"Alexandra ""Alex""",Menendez,[email protected],Miami,1
["Alexandra \"Alex\"", "Menendez", "[email protected]", "Miami", "1"]
the return should be a list and that's where I am landing into a problem. This is what I came up with
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
What I get back instead is
['"Alexandra \\"Alex\\""', 'Menendez', '[email protected]', 'Miami', '1']
Upvotes: 0
Views: 1928
Reputation: 43196
You don't have to do anything. The csv
module will load your data correctly:
import csv
from io import StringIO
infile = StringIO('"Alexandra ""Alex""",Menendez,[email protected],Miami,1')
reader = csv.reader(infile)
for row in reader:
print(row)
# output:
# ['Alexandra "Alex"', 'Menendez', '[email protected]', 'Miami', '1']
Upvotes: 4
Reputation: 119
Say, after converting your sentence into list and iterating over every elements, do the following regsub
Consider 'a' is an element from your list
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)
Upvotes: 0