Reputation: 943
I want to quote a string in the same style as a CSV quoted string.
>>> a='a"b'
>>> print dq(a)
"a""b"
>>>
How can I write the dq
function in Python 2.7?
The obvious solution is '"'+a.replace('"','""')+'"'
but I'm not keen on it. I get the feeling there's a more pythonic way to do it.
There might also be other gotchas within the CSV format (if there is such a thing as "the" in this context) that might bite me. I don't want to use the csv module as I'm not actually writing a CSV file, I'm writing data that will be used pretty much the same as CSV. Maybe I could dive into the csv module implementation and hook into its internals somehow.
Upvotes: 0
Views: 47
Reputation: 11454
You may write to a StringIO
object using the csv
module and you get all the extra quoting dialects for free, as well as tested code.
If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.
For that specific field, what you're writing has all the annoyances CSV can have, so it's CSV. You may wrap the CSV stuff if you want it to remain an implementation detail.
If you want to avoid all the possible gotchas of CSV and its variants, you'll end up reimplementing the whole thing, which is pointless.
Upvotes: 1