I have a CSV file with each fields quoted in double quotes. But some of the fields/strings itself has double quotes inside it and I want to remove them from that particular string.
For example- One of the string in CSV fields is "My name is "Rajesh" Kumar".
Now I want to replace the above string as "My name is Rajesh Kumar", restoring the double quotes outside.
I tried the below code, but unfortunately it replaces all the double quotes.
file_out = csv.writer(open("file", "w"), doublequote=False, escapechar='\\', delimiter=';',quotechar='"')
with open("file", "r") as f:
content = f.read().replace('"', '')
reader = csv.reader(StringIO(content), doublequote=False, escapechar='\\', delimiter=';'quotechar='"')
for row in reader:
print(row)
file_out.writerow(row)
You could replace all quotes in a substring that does not include the first and last characters of your original string.
row = "\"My name is \"Rajesh\" Kumar\""
print(row)
row = row[0] + row[1:-1].replace('\"', '') + row[-1]
print(row)
or
row = "\"My name is \"Rajesh\" Kumar\""
print(row)
row = "\"{}\"".format(row[1:-1].replace('\"', ''))
print(row)
Output:
"My name is "Rajesh" Kumar"
"My name is Rajesh Kumar"
Found another post that basically covers what is being asked: Regular expression replace except first and last characters
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.