What's The Advantage Of Having Multi-line & Single-line String Literals In Python?
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 & mult
Solution 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:
- It isn't always the case that you're using a syntax-highlighting editor
- 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.
Post a Comment for "What's The Advantage Of Having Multi-line & Single-line String Literals In Python?"