Python 三重双引号 vs 双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17643894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Triple-double quote v.s. Double quote
提问by Mingyu
What is the preferred way to write Python doc string?
编写 Python 文档字符串的首选方法是什么?
"""
or "
"""
或者 "
In the book Dive Into Python, the author provides the following example:
在Dive Into Python一书中 ,作者提供了以下示例:
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string."""
In another chapter, the author provides another example:
在另一章中,作者提供了另一个例子:
def stripnulls(data):
"strip whitespace and nulls"
return data.replace(""""Return a foobang
Optional plotz says to frobnicate the bizbaz first.
"""
", "").strip()
Both syntax work. The only difference to me is that """
allows us to write multi-line doc.
两种语法都有效。对我来说唯一的区别是"""
允许我们编写多行文档。
Is there any difference other than that?
除此之外还有什么区别吗?
采纳答案by unutbu
From the PEP8 Style Guide:
来自PEP8 风格指南:
PEP 257describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, e.g.:
"""Return a foobang Optional plotz says to frobnicate the bizbaz first. """
For one liner docstrings, it's okay to keep the closing """ on the same line.
PEP 257描述了良好的文档字符串约定。请注意,最重要的是,结束多行文档字符串的 """ 应该单独在一行上,例如:
##代码##对于单行文档字符串,可以将结束的 """ 保留在同一行上。
PEP 257recommends using triple quotes, even for one-line docstrings:
PEP 257建议使用三重引号,即使是单行文档字符串:
- Triple quotes are used even though the string fits on one line. This makes it easy to later expand it.
- 即使字符串适合一行,也使用三引号。这使得以后扩展它变得容易。
Note that not even the Python standard library itself follows these recommendations consistently. For example,
请注意,即使是 Python 标准库本身也没有始终遵循这些建议。例如,
回答by Blender
They're both strings, so there is no difference. The preferred style is triple double quotes (PEP 257):
它们都是字符串,所以没有区别。首选样式是三重双引号 ( PEP 257):
For consistency, always use
"""triple double quotes"""
around docstrings.Use
r"""raw triple double quotes"""
if you use any backslashes in your docstrings. For Unicode docstrings, useu"""Unicode triple-quoted strings"""
.
为了保持一致性,请始终使用
"""triple double quotes"""
围绕文档字符串。使用
r"""raw triple double quotes"""
,如果你在你的文档字符串使用任何反斜线。对于 Unicode 文档字符串,请使用u"""Unicode triple-quoted strings"""
.
回答by user2514631
No, not really. If you are writing to a file, using triple quotes may be ideal, because you don't have to use "\n" in order to go a line down. Just make sure the quotes you start and end with are the same type(Double or Triple quotes). Here is a reliable resource if you have any more questions:
不,不是真的。如果您正在写入文件,使用三重引号可能是理想的,因为您不必使用 "\n" 来向下一行。只要确保您开始和结束的引号类型相同(双引号或三引号)。如果您还有其他问题,这里是一个可靠的资源: