How to escape comma in string Python 2.7 in a .csv file
10,657
Assuming that you're using the csv module, you don't have to do anything. csv
deals with it for you:
import csv
w = csv.writer(open("result.csv","w"))
w.writerow([1,"a","the big bad, string"])
result:
1,a,"the big bad, string"
If, however, you aren't using import csv
, then you'll want to quote that field:
row = [1, "a", "the big bad, string"]
print ','.join('"%s"'%i for i in row)
Result:
"1","a","the big bad, string"
Author by
Erik Åsland
Updated on June 04, 2022Comments
-
Erik Åsland almost 2 years
I have a string
ven = "the big bad, string"
in a .csv file. I need to escape the,
character using Python 2.7.Currently I am doing this:
ven = "the big bad\, string"
, but when I run the following commandprint ven
, it printsthe big bad\, string
in the terminal.How do I effectively escape the
,
character from this string within a.csv
file so if someone were to dl that file and open it in excel it wouldn't screw everything up? -
Erik Åsland almost 8 yearsThanks. This helped alot.