複数行の文字列の適切なインデントは? 質問する

複数行の文字列の適切なインデントは? 質問する

関数内の Python の複数行文字列の適切なインデントは何ですか?

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

または

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

または、他の何か?

最初の例では、文字列が関数の外側にぶら下がっているのが少し奇妙に見えます。

ベストアンサー1

おそらくあなたは"""

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

改行とスペースは文字列自体に含まれているため、後処理が必要になります。それをしたくない場合や、大量のテキストがある場合は、テキストファイルに別に保存することをお勧めします。テキストファイルがアプリケーションに適しておらず、後処理したくない場合は、おそらく次の方法をお勧めします。

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

複数行の文字列を後処理して不要な部分を削除したい場合は、textwrapモジュールまたはdocstringsの後処理のテクニックペップ257:

def trim(docstring):
    import sys
    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)

おすすめ記事