如何在CSV字段中用空字符替换双引号内的双引号?

时间:2020-02-05 10:50:35

标签: python csv double-quotes

我有一个CSV文件,每个字段都用双引号引起来。但是某些字段/字符串本身内部有双引号,我想从特定的字符串中删除它们。

例如-CSV字段中的字符串之一是“我的名字是“ Rajesh” Kumar”。

现在,我想将上面的字符串替换为“我的名字是Rajesh Kumar”,恢复外面的双引号。

我尝试了以下代码,但不幸的是,它替换了所有双引号。

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)

1 个答案:

答案 0 :(得分:0)

您可以替换不包含原始字符串的开头和结尾字符的子字符串中的所有引号。

row = "\"My name is \"Rajesh\" Kumar\""
print(row)
row = row[0] + row[1:-1].replace('\"', '') + row[-1]
print(row)

row = "\"My name is \"Rajesh\" Kumar\""
print(row)
row = "\"{}\"".format(row[1:-1].replace('\"', ''))
print(row)

输出:

"My name is "Rajesh" Kumar"
"My name is Rajesh Kumar"

找到了另一篇基本上涵盖所要询问内容的帖子:Regular expression replace except first and last characters

相关问题