What's the advantage of having multi-line & single-line string literals in python?

隐身守侯 提交于 2020-01-11 10:24:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/18294318/whats-the-advantage-of-having-multi-line-single-line-string-literals-in-pytho

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!