[python] 파이썬 여러 줄 문자열에 대한 적절한 들여 쓰기

함수 내에서 파이썬 여러 줄 문자열에 적절한 들여 쓰기는 무엇입니까?

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

또는

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

또는 다른 것?

첫 번째 예제에서 문자열이 함수 외부에 매달려있는 것은 이상하게 보입니다.



답변

당신은 아마 """

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

줄 바꿈과 공백은 문자열 자체에 포함되므로이를 사후 처리해야합니다. 그렇게하고 싶지 않고 텍스트가 많으면 텍스트 파일에 별도로 저장하는 것이 좋습니다. 텍스트 파일이 응용 프로그램에서 제대로 작동하지 않고 후 처리를 원하지 않으면 아마도

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

필요없는 부품을 제거 textwrap하기 위해 여러 줄 문자열을 후 처리하려면 PEP 257에 제시된 모듈 또는 후 처리 문자열을위한 기술을 고려해야합니다 .

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)


답변

textwrap.dedent함수를 사용 하면 source에서 올바른 들여 쓰기 로 시작한 다음 사용하기 전에 텍스트에서 제거 할 수 있습니다.

다른 사람들이 지적했듯이, 이것은 리터럴에 대한 추가 함수 호출이라는 것입니다. 코드에서 이러한 리터럴을 배치 할 위치를 결정할 때이 점을 고려하십시오.

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)

\로그 메시지 리터럴 의 후행 은 줄 바꿈이 리터럴에 없는지 확인하는 것입니다. 그런 식으로 리터럴은 빈 줄로 시작하지 않고 다음 전체 줄로 시작합니다.

from의 반환 값은 textwrap.dedent문자열의 각 줄에서 모든 공통 선행 공백 들여 쓰기가 제거 된 입력 문자열입니다 . 위의 log_message값은 다음과 같습니다.

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


답변

다음 inspect.cleandoc과 같이 사용하십시오 .

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

상대적 들여 쓰기는 예상대로 유지됩니다. 아래에 주석을 달았 듯이 앞에 빈 줄을 유지하려면을 사용하십시오 textwrap.dedent. 그러나 이것은 또한 첫 줄 바꿈을 유지합니다.

참고 : 구조를 명확히하기 위해 관련 컨텍스트에서 논리 코드 블록을 들여 쓰는 것이 좋습니다. 예를 들어 변수에 속하는 여러 줄 문자열 string입니다.


답변

다른 답변에서 누락 된 것으로 보이는 한 가지 옵션은 다음과 같습니다 (naxa의 의견에서 깊이 언급되어 있음).

def foo():
    string = ("line one\n"          # Add \n in the string
              "line two"  "\n"      # Add "\n" after the string
              "line three\n")

이렇게하면 올바른 정렬이 가능하고 라인을 암시 적으로 결합하며 여전히 줄 바꿈을 유지합니다. 이는 여러 줄 문자열을 사용하려는 이유 중 하나입니다.

사후 처리는 필요하지 않지만 \n줄을 끝내려는 특정 위치 에 수동으로 추가해야합니다 . 인라인 또는 별도의 문자열로 표시됩니다. 후자는 복사하여 붙여 넣기가 더 쉽습니다.


답변

더 많은 옵션. 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 dedent를 사용하면 동일한 합리적인 결과를 얻을 수 있습니다. textwrap dedent 함수에는 첫 번째 예제와 함께 빈 줄이 생깁니다.

명백한 단점은 textwrap이 표준 라이브러리에 있고 matplotlib가 외부 모듈이라는 것입니다.

일부 단점은 … dedent 함수는 문자열을 정의하는 위치에서 코드를 더 읽기 쉽게 만들지 만 나중에 사용 가능한 형식으로 문자열을 가져 오려면 처리해야합니다. docstring에서는 대부분의 docstring 사용이 필요한 처리를 수행하므로 올바른 들여 쓰기를 사용해야합니다.

내 코드에 긴 문자열이 아닌 경우 긴 문자열을 둘러싸는 들여 쓰기에서 제외시키는 다음과 같은 추악한 코드가 있습니다. “아름다움이 못생긴 것보다 낫다”는 것은 분명 실패하지만, 다른 대안보다 더 단순하고 명백하다고 주장 할 수있다.

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()


답변

빠르고 쉬운 솔루션을 원하고 개행을 입력하지 않으려면 다음과 같이 목록을 선택할 수 있습니다.

def func(*args, **kwargs):
    string = '\n'.join([
        'first line of very long string and',
        'second line of the same long thing and',
        'third line of ...',
        'and so on...',
        ])
    print(string)
    return


답변

나는 선호한다

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

또는

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