I am fairly new to python. Was following the suggestions from here trying to force a string to be output with a single set of double quotes (e.g., "my_string"
) but it always ends up being printed as such: """my_string"""
Any idea why?
I tried:
'"' + my_string + '"'
and
f'"{self.args["name"]}"'
and str(my_string)
and "\"" + my_String + "\""
but same behavior:
"""my_string"""
Code snippet:
def print_out(self):
self.args = {}
self.args["name"] = 001
self.bla = 1
self.tra = 0
self.val = 0.12445
with open("my_file", "w") as fout:
tsv = csv.writer(fout, delimiter="\t")
tsv.writerow(["name", "bla", "tra", "hehe"])
tsv.writerow(
[f'"{self.args["name"]}"', self.bla, self.tra, round(self.val, 2)]
)
In the above example, the self.args["name"]
is printed as """001"""
Thanks
CSV files come in many different dialects. In their simplest form, they are just a list of strings, separated by a delimiter. In this case, you are using a tab.
The problems start when you want a value that contains a delimiter; then you have to escape the tab in some way to prevent a parser from treating it as such. One way of doing that is to quote the entire field.
But now, how do you include a quote in the value of a field? By default, you quote the field and escape the literal quotes by doubling them.
So,
"001"
becomes"""001"""
because the value"001"
has to be quoted, and the literal"
each gets replaced by""
. A parser (using this default dialect) would see"..."
and strip the outer most quotes, then replace each remaining pair of quotes with a single quote to get"001"
back from"""001"""
.There appear to be a number of ways to disable quoting of double quotes, and which one you need may depend on the other kind of data you are using. One simple way is to simply set the
quotechar
argument toNone
when creating the CSV writer.See Dialects and Formatting Parameters for more information about how exactly data is quoted and/or escaped in a CSV file.
A demonstration:
(Each call to
f.writerow
shows the data written to standard output, followed by its return value.)