728x90
반응형
질문 : Python 여러 줄 문자열에 대한 적절한 들여 쓰기
함수 내에서 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에 textwrap
모듈 또는 후 처리 독 스트링 기술을 고려해야합니다.
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/proper-indentation-for-python-multiline-strings
728x90
반응형
'프로그래밍 언어 > Python' 카테고리의 다른 글
Python의 '__enter__'및 '__exit__'설명 (0) | 2022.01.06 |
---|---|
다른 Python 버전에서 가상 환경을 사용하는 방법 (0) | 2022.01.06 |
Python에서 예외를 출력하는 방법 (0) | 2021.12.19 |
파이썬에서 반복 가능한 객체인지 확인하는 방법 (0) | 2021.12.19 |
파이썬에서 문자열의 부분 문자열을 얻는 방법 (0) | 2021.12.19 |