[Tutor] Writing to CSV string containing quote and comma
Steven D'Aprano
steve at pearwood.info
Tue Dec 10 00:46:04 CET 2013
On Mon, Dec 09, 2013 at 11:14:38PM +0000, J Sutar wrote:
> Steven, I updated the very last line of code as below, as I need to get the
> word wrapped around quotes. Is that a good way of achieving that?
[...]
> writer.writerow([str(n) + " " + chr(34) + s + chr(34) for n, s in
> zip(numbers, words)])
Not really a good way, no.
Python has two different quote characters ' and " so you can use one for
delimiters and the other inside the string:
s = "this string contains ' single quote"
s = 'this string contains " double quote'
If you need both, you can escape the one that matches the delimiter:
s = 'this string contains both \' single and " double quotes'
Rather than assembling the final string piece by piece using string
concatenation (the + operator), it is usually better to use template
strings. Python has three standard ways to do template strings:
the % operator (like C's printf);
the format() method;
the string module's Template class.
I won't talk about the Template class, as it is fairly specialised and
less convenient. Compare your version:
str(number) + " " + chr(34) + word + chr(34)
with the formatting versions:
'%d "%s"' % (number, word)
'{0} "{1}"'.format(number, word)
In Python 2.7, you can abbreviate that last one slightly:
'{} "{}"'.format(number, word)
Either should be preferred to building the string by hand with + signs.
The rule of thumb I use is to say that adding two substrings together is
fine, if I need more than one + sign I use a format string. So these
would be okay:
plural = word + "s"
line = sentence + '\n'
but anything more complex and I would use % or format().
--
Steven
More information about the Tutor
mailing list