반응형
함수 내에서 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
반응형
'파이썬' 카테고리의 다른 글
파이썬 플라스크 값 오류보기 기능이 응답을 반환하지 않았습니다. (0) | 2020.12.12 |
---|---|
파이썬에서 배열을 선언하고 채우는 방법은 무엇입니까? (0) | 2020.12.12 |
파이썬 람다 함수를 사용하여 중첩 된 목록에서 합계 찾기 (0) | 2020.12.11 |
파이썬에서 백 슬래시로 문자열 분할 (0) | 2020.12.11 |
파이썬 NaN (Pandas)에서 필터링하는 방법은 무엇입니까? (0) | 2020.12.11 |
댓글