source

여러 줄 문자열의 올바른 들여쓰기입니까?

factcode 2022. 9. 16. 23:00
반응형

여러 줄 문자열의 올바른 들여쓰기입니까?

함수 내 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")

필요하지 않은 부분을 잘라내기 위해 여러 줄 문자열을 후처리하려면 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)

이 기능을 사용하면 소스에서 올바른 들여쓰기로 시작한 후 사용하기 전에 텍스트에서 제거할 수 있습니다.

다른 일부에서 지적한 바와 같이 이 문제는 문자 그대로 추가 함수 호출이라는 것입니다. 코드 내에서 이러한 리터럴을 배치할 위치를 결정할 때 이 점을 고려하십시오.

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!

다음과 같이 사용:

import inspect

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

예상대로 상대적 들여쓰기가 유지됩니다.다음 설명과 같이 빈 행을 계속 사용할 경우 를 사용합니다.단, 첫 번째 줄 바꿈도 유지됩니다.

주의: 구조를 명확히 하기 위해 관련 컨텍스트에서 코드 논리 블록을 들여쓰는 것이 좋습니다.예: 변수에 속하는 여러 줄 문자열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 전용식을 사용하면 동일한 합리적인 결과를 얻을 수 있습니다.텍스트랩 전용 함수는 첫 번째 예시와 함께 선두에 공백 행이 있습니다.

분명한 단점은 텍스트랩이 표준 라이브러리에 있는 반면 matplotlib은 외부 모듈이라는 것입니다.

여기 약간의 트레이드오프가 있습니다.전용 함수는 문자열이 정의된 곳에서 코드를 더 쉽게 읽을 수 있게 하지만 문자열을 사용 가능한 형식으로 가져오려면 나중에 처리해야 합니다.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\
"""

내 말은, 줄 끝을 피해 들어가라는 거야.

def foo():
    return "{}\n"\
           "freq: {}\n"\
           "temp: {}\n".format( time, freq, temp )

스크립트내에서 「기능외에 행업」하는 등, 인쇄용의 문서 문자열의 식별 레벨을 삭제/수정하는 심플한 1-라이너를 찾고 있었습니다.

제가 하게 된 일은 다음과 같습니다.

import string
def myfunction():

    """
    line 1 of docstring
    line 2 of docstring
    line 3 of docstring"""

print str(string.replace(myfunction.__doc__,'\n\t','\n'))[1:] 

탭 키가 아닌 공백(예: 4)으로 들여쓰기를 하는 경우에는 다음과 같은 방법을 사용합니다.

print str(string.replace(myfunction.__doc__,'\n    ','\n'))[1:]

docstring을 다음과 같이 하려면 첫 번째 문자를 삭제할 필요가 없습니다.

    """line 1 of docstring
    line 2 of docstring
    line 3 of docstring"""

print string.replace(myfunction.__doc__,'\n\t','\n') 

문자열의 경우 문자열을 처리한 직후에 사용할 수 있습니다.문서 문자열의 경우 대신 기능을 처리한 후 수행해야 합니다.여기 아직 읽을 수 있는 두 가지 해결책이 있습니다.

class Lstrip(object):
    def __rsub__(self, other):
        import re
        return re.sub('^\n', '', re.sub('\n$', '', re.sub('\n\s+', '\n', other)))

msg = '''
      Lorem ipsum dolor sit amet, consectetur adipiscing 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 ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.
      ''' - Lstrip()

print msg

def lstrip_docstring(func):
    func.__doc__ = func.__doc__ - Lstrip()
    return func

@lstrip_docstring
def foo():
    '''
    Lorem ipsum dolor sit amet, consectetur adipiscing 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 ex ea
    commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
    velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
    cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
    est laborum.
    '''
    pass


print foo.__doc__

첫 번째 옵션은 좋은 옵션입니다. 들여쓰기 포함.python 스타일 - 코드의 가독성을 제공합니다.

올바르게 표시하려면:

print string.lstrip()

텍스트를 표시하는 방법에 따라 다릅니다.모두 왼쪽 정렬되도록 하려면 첫 번째 스니펫과 같이 형식을 지정하거나 모든 공간을 왼쪽 정렬하여 행을 반복하십시오.

언급URL : https://stackoverflow.com/questions/2504411/proper-indentation-for-multiline-strings

반응형