Question

I know the triple quote strings are used as docstrings, but is there a real need to have two string literals?

Are there any use case when identifying between single-line & multi-line is useful.

in Clojure we have 1 string literal, is multi-line and we use it as docstring. So why the difference in python?

Était-ce utile?

La solution

The advantage of having to be explicit about creating a multi-line string literal is probably best demonstrated with an example:

with open("filename.ext) as f:
    for line in f:
        print(line.upper())

Of course, any decent syntax-highlighting editor will catch that, but:

  1. It isn't always the case that you're using a syntax-highlighting editor
  2. Python has no control over what editor you are using.

Two of Python's design principles are that

  • errors should never pass silently, and
  • explicit is better than implicit.

Outside docstrings, multi-line strings are rarely used in Python, so the example above is much more likely to occur (everyone mistypes sometimes) than the case where you want a multi-line string, but forgot to explicitly say so by triple-quoting.

It's similar to Python's use of significant whitespace, in that enforcing good, consistent indentation practice means that errors are much more easily caught than in e.g. a brace-delimited language.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top