Triple-quoted strings hath not the Python-nature

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Wed Oct 22 23:44:54 EDT 2008


On Tue, 21 Oct 2008 21:58:57 +1300, Lawrence D'Oliveiro wrote:

> If triple-quoted strings had the Python-nature, then they would take
> indentation into account. Thus:
> 
>     """this
>      is a
>      multi-line
>     string."""
> 
> would be equivalent to
> 
>     "this\n is a\n multi-line\nstring."
> 
> and not
> 
>     "this\n     is a\n     multi-line\n    string."

I disagree. Triple-quoted strings are exactly the same as other strings: 
they capture *exactly* what you put in them, and don't add or subtract 
characters which the language designer imagines might be irrelevant for 
some people some of the time.

" xyz " gives the exact string " xyz " and not "xyz", no matter how 
convenient such behaviour would be for those who want only "xyz". If you 
want to strip whitespace from the string, you can strip whitespace from 
the string yourself.

Similarly 

"""abc
   xyz   """

results in the exact string you put inside the quotes. Python doesn't try 
to guess whether or not the spaces are significant. If you want to strip 
whitespace, or any other character, you can do so yourself.

In other words, triple-quoted strings absolutely DO have the Python-
nature, because they refuse to guess what the programmer intends to do 
with the string later. If you don't want the spaces, either don't put 
them in in the first place, or remove them yourself. Don't expect Python 
to guess whether you want the spaces or not.



-- 
Steven



More information about the Python-list mailing list