ProgramingTip

따옴표 삼중 따옴표로 묶인 여러 줄의 추가 들여 쓰기를 제거하는 방법은 무엇입니까?

bestdevel 2020. 12. 14. 20:36
반응형

따옴표 삼중 따옴표로 묶인 여러 줄의 추가 들여 쓰기를 제거하는 방법은 무엇입니까?


사용자가 펼쳐 놓거나 코드를 입력 한 다음 모든 줄을 들여 쓰면서 장면 뒤의 주요 메소드에 넣는 Python 편집기가 있습니다. 많은 문제는 사용자에게 여러 줄의 많은 줄이있는 경우 모든 공백에 탭을 삽입하여 전체에 대한 들여 쓰기에 영향을 미친다는 것입니다. 문제 펼쳐는 다음과 같이 간단합니다.

"""foo
bar
foo2"""

따라서 주요 방법에서 다음과 같이 시청.

def main():
    """foo
    bar
    foo2"""

이제는 모든 줄 시작 부분에 추가 탭이 있습니다.


따라서 내가 선택한 이해하면 사용자 입력을 취하고 들여 쓰기하여 나머지 프로그램에 추가하고 전체 프로그램을 실행합니다.

따라서 사용자 입력을 프로그램에 넣은 후에는 기본적으로 강제 들여 쓰기를 돌리는 정규식을 사용할 수 있습니다. 예를 들면 다음과 같습니다. 따옴표 세 개 내에서 "새 줄 표시 자"와 4 개의 공백 (또는 탭)을 "새 줄 표시 자"로만 바꿉니다.


표준 라이브러리의 textwrap.dedent 는 엉뚱한 들여 쓰기를 자동으로 취소 할 수 있습니다.


내가보기에, 여기에 더 나은 대답이 될 수 있습니다 inspect.cleandoc. 이 기능을 수행하는 것이 textwrap.dedent아니라 textwrap.dedent행간에 있는 문제를 해결합니다 .

아래 예는 차이점을 보여줍니다.

   >>> import textwrap
   >>> import inspect
   >>> x = """foo bar
       baz
       foobar
       foobaz
       """
   >>> inspect.cleandoc(x)
   'foo bar\nbaz\nfoobar\nfoobaz'
   >>> textwrap.dedent(x)
   'foo bar\n    baz\n    foobar\n    foobaz\n'
   >>> y = """
   ...     foo
   ...     bar
   ... """
   >>> textwrap.dedent(y)
   '\nfoo\nbar\n'
   >>> inspect.cleandoc(y)
   'foo\nbar'

여러 줄 없던 것의 첫 번째 항목은 ""라고 말할 수 있습니다. 다음과 같이 자유롭게 사용할 수 있습니다.

def main():
    """foo
bar
foo2"""
    pass

그리고 그것은 옳은 일을 할 것입니다.

반면에 그것은 읽을 수 없으며 Python은 그것을 알고 있습니다. 따라서 독 스트링의 두 번째 줄에 공백이 포함 된 help()경우 독 스트링을 보는 데 사용할 때 해당 공백이 제거됩니다 . 따라서 help(main)아래 help(main2)는 동일한 도움말 정보를 생성합니다.

def main2():
    """foo
    bar
    foo2"""
    pass

내가 보는 유일한 방법은 두 번째로 시작하는 각 줄에 대해 처음 n 개의 탭을 제거하는 것입니다. 여기서 n은 기본 방법의 알려진 식별입니다.

그 식별이 사전에 알려지지 않은 경우-삽입하기 전에 후행 개행을 추가하고 마지막 행에서 탭 수를 제거 할 수 있습니다.

세 번째 해결책은 데이터를 구문 분석하고 여러 줄 따옴표의 시작 부분을 찾고 닫을 때까지 모든 줄에 ID를 추가하지 않는 것입니다.

더 나은 해결책이 있다고 생각합니다 ..


사이의 차이를 표시 textwrap.dedent하고 inspect.cleandoc조금 더 선명도와를 :

선행 부분이 들여 쓰기되지 않은 동작

import textwrap
import inspect

string1="""String
with
no indentation
       """
string2="""String
        with
        indentation
       """
print('string1 plain=' + repr(string1))
print('string1 inspect.cleandoc=' + repr(inspect.cleandoc(string1)))
print('string1 texwrap.dedent=' + repr(textwrap.dedent(string1)))
print('string2 plain=' + repr(string2))
print('string2 inspect.cleandoc=' + repr(inspect.cleandoc(string2)))
print('string2 texwrap.dedent=' + repr(textwrap.dedent(string2)))

산출

string1 plain='String\nwith\nno indentation\n       '
string1 inspect.cleandoc='String\nwith\nno indentation\n       '
string1 texwrap.dedent='String\nwith\nno indentation\n'
string2 plain='String\n        with\n        indentation\n       '
string2 inspect.cleandoc='String\nwith\nindentation'
string2 texwrap.dedent='String\n        with\n        indentation\n'

앞부분이 들여 쓰기 된 동작

string1="""
String
with
no indentation
       """
string2="""
        String
        with
        indentation
       """

print('string1 plain=' + repr(string1))
print('string1 inspect.cleandoc=' + repr(inspect.cleandoc(string1)))
print('string1 texwrap.dedent=' + repr(textwrap.dedent(string1)))
print('string2 plain=' + repr(string2))
print('string2 inspect.cleandoc=' + repr(inspect.cleandoc(string2)))
print('string2 texwrap.dedent=' + repr(textwrap.dedent(string2)))

산출

string1 plain='\nString\nwith\nno indentation\n       '
string1 inspect.cleandoc='String\nwith\nno indentation\n       '
string1 texwrap.dedent='\nString\nwith\nno indentation\n'
string2 plain='\n        String\n        with\n        indentation\n       '
string2 inspect.cleandoc='String\nwith\nindentation'
string2 texwrap.dedent='\nString\nwith\nindentation\n'

참고 URL : https://stackoverflow.com/questions/1412374/how-to-remove-extra-indentation-of-python-triple-quoted-multi-line-strings

반응형