函数中Python多行字符串的缩进方式是怎样的?

    def method():
        string = """line one
line two
line three"""

or

    def method():
        string = """line one
        line two
        line three"""

还是别的什么?

在第一个例子中,将字符串挂在函数外面看起来有点奇怪。


当前回答

dedent函数允许在源代码中以正确的缩进开始,然后在使用之前将其从文本中剥离。

正如其他人所指出的那样,这是对字面量的额外函数调用;在决定在代码中放置这些文字的位置时,要考虑到这一点。

import textwrap

def frobnicate(param):
    """ Frobnicate the scrognate param.

        The Weebly-Ruckford algorithm is employed to frobnicate
        the scrognate to within an inch of its life.

        """
    prepare_the_comfy_chair(param)
    log_message = textwrap.dedent("""\
            Prepare to frobnicate:
            Here it comes...
                Any moment now.
            And: Frobnicate!""")
    weebly(param, log_message)
    ruckford(param)

日志消息字面量中尾随的\是为了确保换行符不在字面量中;这样,字面量就不会以空行开始,而是以下一行开始。

dedent的返回值是删除了字符串每行上所有常用前导空格缩进的输入字符串。所以上面的log_message值将是:

Prepare to frobnicate:
Here it comes...
    Any moment now.
And: Frobnicate!

其他回答

使用检查。Cleandoc像这样:

import inspect

def method():
    string = inspect.cleandoc("""
        line one
        line two
        line three""")

相对压痕将按预期保持。正如下面所评论的,如果你想保持前面的空行,使用textwrap.dedent。但是,这也保留了第一个换行符。

注意:在相关上下文下缩进代码逻辑块以澄清结构是一种良好的实践。例如,多行字符串属于变量字符串。

这取决于您希望文本如何显示。如果你想让它全部向左对齐,那么要么像第一个代码片段那样格式化它,要么遍历所有的行,向左修剪所有的空间。

更多的选择。在启用了pylab的Ipython中,dedent已经在名称空间中。我检查了一下,它来自matplotlib。或者可以导入:

from matplotlib.cbook import dedent

在文档中,它指出它比文本封装的等效程序要快,在我用ipython进行的快速测试中,它的平均速度确实快3倍。它还有一个好处,它丢弃了任何前导空行,这让你可以灵活地构造字符串:

"""
line 1 of string
line 2 of string
"""

"""\
line 1 of string
line 2 of string
"""

"""line 1 of string
line 2 of string
"""

在这三个示例上使用matplotlib依赖项将得到相同的合理结果。textwrap dedent函数将在第一个示例中有一个前导空行。

明显的缺点是textwrap在标准库中,而matplotlib是外部模块。

这里有一些权衡……在定义字符串的地方,dedent函数使代码更具可读性,但需要稍后处理以获得可用格式的字符串。在文档字符串中,很明显应该使用正确的缩进,因为大多数使用文档字符串都会执行所需的处理。

当我需要一个非长字符串在我的代码中,我发现以下承认丑陋的代码,我让长字符串退出封闭缩进。“美丽总比丑陋好”这句话绝对不合适,但有人可能会说,它比抑扬抑扬的说法更简单、更明确。

def example():
    long_string = '''\
Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip.\
'''
    return long_string

print example()

第一个选项是好的-包括缩进。 它是python风格的-提供了代码的可读性。

正确显示:

print string.lstrip()

dedent函数允许在源代码中以正确的缩进开始,然后在使用之前将其从文本中剥离。

正如其他人所指出的那样,这是对字面量的额外函数调用;在决定在代码中放置这些文字的位置时,要考虑到这一点。

import textwrap

def frobnicate(param):
    """ Frobnicate the scrognate param.

        The Weebly-Ruckford algorithm is employed to frobnicate
        the scrognate to within an inch of its life.

        """
    prepare_the_comfy_chair(param)
    log_message = textwrap.dedent("""\
            Prepare to frobnicate:
            Here it comes...
                Any moment now.
            And: Frobnicate!""")
    weebly(param, log_message)
    ruckford(param)

日志消息字面量中尾随的\是为了确保换行符不在字面量中;这样,字面量就不会以空行开始,而是以下一行开始。

dedent的返回值是删除了字符串每行上所有常用前导空格缩进的输入字符串。所以上面的log_message值将是:

Prepare to frobnicate:
Here it comes...
    Any moment now.
And: Frobnicate!