拥有多行&的优势是什么? python中的单行字符串文字? [英] What's the advantage of having multi-line & single-line string literals in python?

查看:146
本文介绍了拥有多行&的优势是什么? 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 & multi-line is useful.

在Clojure中,我们有1个字符串文字,它是多行的,我们将其用作docstring.那么为什么python的区别呢?

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

推荐答案

必须明确地说明创建多行字符串文字的优点,例如:

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. 并非总是使用语法突出显示的编辑器
  2. Python无法控制您正在使用的编辑器.

Python的两个设计原则是

Two of Python's design principles are that

  • 错误绝不能默默传递,
  • 显式优于隐式.

在文档字符串之外,多行字符串在Python中很少使用,因此,与需要多行字符串的情况相比,上面的示例更有可能发生(有时每个人键入错误),但是忘了明确地这样说三引号.

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.

这与Python使用大量空白相似,因为执行良好,一致的缩进实践意味着错误比在例如中更容易被发现.大括号分隔的语言.

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.

这篇关于拥有多行&的优势是什么? python中的单行字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆