What is prefered: 'string' or "string"? (Should be in PEP8 ?)

François Pinard pinard at iro.umontreal.ca
Tue Apr 23 13:13:56 EDT 2002


[Petr Prikryl]

> [...] is there any preference of single or double quotes when writing
> strings?  [...]  Thanks for your opinions,

When I came to Python, I asked myself the same question, and discussed the
matter with this list as you do.  I hesitated for a while before adopting
a consistent style.  Here is the rule I finally gave myself.

If the string is text, or even sentence fragments meant to be read by
a human, I use double quotes.  If the string is anything else, a file
name, a character, the name of an identifier, etc., I use single quotes.
When in doubt, I ask myself: would this string be translated or not if the
program was later internationalised?  I agree with you that single quotes
are less noisy, yet the fact is that single quotes often appear in human
text (as apostrophes).

Some people tend to merely transport in Python habits coming from other
languages.  We need a very good reason for doing that, in my opinion, as
reasons which are good in some languages are pretty meaningless in Python.
For example, in Perl and shell, I use double quotes when I want to allow
interpolation, and single quotes when I want to inhibit it: so I could
translate this usage in using double quotes for formats and single quotes
for the rest, but it looks to me that this is poor usage of the available
difference.  C mandates double quotes for strings and single quotes for
characters, this distinction is not really useful nor worth in Python.
Best is to develop a style which much more fit to Python idiosyncrasies.

Other details.  For Python, I tend to use raw strings (the `r' prefix to
strings) consistently for regular expressions (especially with SPARK and
PLY in these days :-), even if there is no embedded backslashes.  I use
triple single quoted strings for grammar rules, and only in SPARK so far.
I limit triple double quoted strings for long strings, meant to be read
by a human, having embedded newlines; the first line is always written
with an escaped newline immediately after the initial triple double quote,
so the first line of text is flushed left, aligned with the others.

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list