Python多行字符串的适当缩进

2024-04-19 21:53:03 发布

您现在位置:Python中文网/ 问答频道 /正文

函数中Python多行字符串的适当缩进是什么?

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

或者

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

或者别的什么?

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


Tags: 函数字符串stringdeflineonemethod例子
3条回答

^{}函数允许从源代码中的正确缩进开始,然后在使用前将其从文本中删除。

正如其他一些人所指出的,权衡的结果是,这是对文本的额外函数调用;在决定将这些文本放在代码中的位置时,要考虑到这一点。

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)

日志消息文本中的尾部\是为了确保换行符不在文本中;这样,文本就不会以空行开头,而是以下一整行开头。

来自textwrap.dedent的返回值是输入字符串,该字符串的每一行上都删除了所有公共前导空白缩进。所以上面的log_message值将是:

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

你可能想和"""排队

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

由于换行符和空格包含在字符串本身中,因此必须对其进行后处理。如果您不想这样做,而且您有大量的文本,您可能希望将其单独存储在一个文本文件中。如果一个文本文件不适合你的应用程序并且你不想进行后处理,我可能会

def foo():
    string = ("this is an "
              "implicitly joined "
              "string")

如果要对多行字符串进行后处理以删除不需要的部分,则应考虑^{}模块或PEP 257中提供的后处理docstring的技术:

def trim(docstring):
    if not docstring:
        return ''
    # Convert tabs to spaces (following the normal Python rules)
    # and split into a list of lines:
    lines = docstring.expandtabs().splitlines()
    # Determine minimum indentation (first line doesn't count):
    indent = sys.maxint
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))
    # Remove indentation (first line is special):
    trimmed = [lines[0].strip()]
    if indent < sys.maxint:
        for line in lines[1:]:
            trimmed.append(line[indent:].rstrip())
    # Strip off trailing and leading blank lines:
    while trimmed and not trimmed[-1]:
        trimmed.pop()
    while trimmed and not trimmed[0]:
        trimmed.pop(0)
    # Return a single string:
    return '\n'.join(trimmed)

像这样使用^{}

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

将按预期保持相对缩进。如下面的commented所示,如果要保留前面的空行,请使用^{}。然而,这也保持了第一行中断。

Note: It's good practice to indent logical blocks of code under its related context to clarify the structure. E.g. the multi-line string belonging to the variable string.

相关问题 更多 >