Question about quoting style.

J. Cliff Dyer jcd at sdf.lonestar.org
Mon Oct 1 20:25:09 EDT 2007


Bruno Desthuilliers wrote:
> Steven W. Orr a écrit :
>   
>> Python has a number of "quoting" 'options' to help """with
>> times when""" one way may be more convenient than another.
>>
>> In the world of shell scripting, I use a technique that I call minimal 
>> quoting. It works like this:
>>
>> foo=bar            # No quotes needed
>> echo $foo        # Also none needed
>> baz='Hello there'    # Don't use double quotes. No iterpolation.
>> qaz="$baz $foo and grill" # Interpolation needs double quotes.
>>
>> Is there some sort of best practices approach for when different types 
>> of quoting should be employed?
>>     
>
> First point is that Python has no "variable interpolation". Second point 
> is in Python, quoting style makes no difference wrt escape sequences 
> (\n, \t etc). Third point is that quoting is not optional when it comes 
> to string literals - but I guess you knew this one already !-)
>
> Where it makes a difference is that "triple-quoted" string literals 
> preserves newlines (ok, I guess you knew this too)
>
> IOW, it's mostly a matter of commodity: use double quotes when you don't 
> want to bother escaping sngle quotes, and vice-versa. As far as I'm 
> concerned, and since it's quite more common to have a single quote than 
> a double one in a string literal, I tend to use double-quoted strings by 
> default. But YMMV !-)
>
>   
You missed another dimension of python string types.

r'Raw strings are useful when \escaping backslashes.  Use them with
regular expressions.'
r"These are also raw.  Also use them when talking about escape sequences
like \n"
r"""Same for "\n" Here"""

u'Unicode strings are useful for multilingual or non-latin text. 
I\u2019d recommend reading more about Python's unicode handling.  It can
be a bit tricky for newcomers.'

Cheers,
Cliff



More information about the Python-list mailing list