Programing

파이썬 스타일-문자열로 줄 연속?

lottogame 2020. 6. 16. 21:44
반응형

파이썬 스타일-문자열로 줄 연속? [복제]


파이썬 스타일 규칙을 준수하기 위해 편집자를 최대 79 열로 설정했습니다.

PEP에서는 대괄호, 괄호 및 중괄호 안에 파이썬의 묵시적 연속을 사용하는 것이 좋습니다. 그러나 col 한계에 도달했을 때 문자열을 처리 할 때 조금 이상해집니다.

예를 들어, 여러 줄을 사용하려고

mystr = """Why, hello there
wonderful stackoverflow people!"""

돌아올 것이다

"Why, hello there\nwonderful stackoverflow people!"

이것은 작동합니다 :

mystr = "Why, hello there \
wonderful stackoverflow people!"

그것이 이것을 반환하기 때문에 :

"Why, hello there wonderful stackoverflow people!"

그러나 명령문이 몇 블록 들여 쓰기되면 이상한 것처럼 보입니다.

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
wonderful stackoverflow people!"

두 번째 줄을 들여 쓰기하려고하면 :

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
            wonderful stackoverflow people!"

문자열은 다음과 같이 끝납니다.

"Why, hello there                wonderful stackoverflow people!"

이 문제를 해결하는 유일한 방법은 다음과 같습니다.

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there" \
            "wonderful stackoverflow people!"

나는 더 좋아하지만 눈에 다소 불안합니다. 어딘가 한가운데에 줄이있는 것처럼 보입니다. 이것은 적절한 것을 생성합니다 :

"Why, hello there wonderful stackoverflow people!"

그래서 내 질문은-이 작업을 수행하는 방법에 대한 사람들의 권장 사항은 무엇이며 스타일 가이드에 누락 된 것이 있습니까?

감사.


이후 인접한 문자열 리터럴은 단일 문자열로 자동으로 공동입니다 PEP 8에서 권장하는대로, 당신은 단지 괄호 안에 내포 된 행 계속 사용할 수 있습니다 :

print("Why, hello there wonderful "
      "stackoverflow people!")

자동 연결을 호출하는 괄호를 사용한다고 지적하십시오. 명세서에서 이미 사용하고 있다면 괜찮습니다. 그렇지 않으면 괄호를 삽입하는 대신 '\'를 사용합니다 (대부분의 IDE가 자동으로 수행하는 작업). 들여 쓰기는 PEP8과 호환되도록 문자열 연속을 정렬해야합니다. 예 :

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

또 다른 가능성은 textwrap 모듈을 사용하는 것입니다. 이것은 또한 질문에서 언급했듯이 "어딘가 한가운데 앉아있는 끈"의 문제를 피합니다.

import textwrap
mystr = """\
        Why, hello there
        wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))

나는이 문제를 해결했습니다.

mystr = ' '.join(
        ["Why, hello there",
         "wonderful stackoverflow people!"])

과거에. 완벽하지는 않지만 줄 바꿈이 필요없는 매우 긴 문자열에는 훌륭하게 작동합니다.


이것은 매우 깨끗한 방법입니다.

myStr = ("firstPartOfMyString"+
         "secondPartOfMyString"+
         "thirdPartOfMyString")

참고 URL : https://stackoverflow.com/questions/5437619/python-style-line-continuation-with-strings

반응형