본문 바로가기
파이썬

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

by º기록 2020. 12. 12.
반응형

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


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)

 

참조 페이지 https://stackoverflow.com/questions/2504411

 

 

반응형

댓글