Programing

긴 줄을 파이썬으로 감싼다

lottogame 2020. 5. 14. 07:58
반응형

긴 줄을 파이썬으로 감싼다


이 질문에는 이미 답변이 있습니다.

들여 쓰기를 희생하지 않고 파이썬에서 긴 줄을 어떻게 감쌀 수 있습니까?

예를 들면 다음과 같습니다.

def fun():
    print '{0} Here is a really long sentence with {1}'.format(3, 5)

이것이 79 자의 권장 한계를 초과한다고 가정하십시오. 내가 읽는 방식은 여기에 들여 쓰는 방법입니다.

def fun():
    print '{0} Here is a really long \
sentence with {1}'.format(3, 5)

그러나이 방법을 사용하면 연속 줄의 들여 쓰기가의 들여 쓰기와 일치합니다 fun(). 좀 못 생겼어 누군가 내 코드를 통과했다면이 print문장으로 인해 들여 쓰기가 고르지 않은 것처럼 보입니다 .

코드 가독성을 희생하지 않으면 서 이와 같은 줄을 효과적으로 들여 쓰려면 어떻게해야합니까?


def fun():
    print(('{0} Here is a really long '
           'sentence with {1}').format(3, 5))

C와 마찬가지로 인접한 문자열 리터럴은 컴파일 타임에 연결됩니다. http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation 은 자세한 정보를 시작하기에 좋은 장소입니다.


두 가지 위에서 언급되지 않은 접근하지만, 모두의은과 함께하는 준수하는 방식으로 문제를 해결할 수있는 PEP 8 당신이 당신의 공간을보다 효율적으로 사용할 수 있도록 할 수 있습니다. 그들은:

msg = (
    'This message is so long, that it requires '
    'more than {x} lines.{sep}'
    'and you may want to add more.').format(
        x=x, sep=2*'\n')
print(msg)

괄호를 사용하여 순수한 문자열 사이에 더하기 부호를 추가하지 않고 명시적인 줄 연속 '\'(못되거나 혼란스러운)없이 여러 줄에 결과를 분산시키는 방법에 주목하십시오. 장점은 아래에 설명 된 것과 동일하지만 차이점은 어디에서나 할 수 있다는 것입니다. 이전 대안과 비교하여 코드를 검사 할 때 시각적으로 더 좋습니다. 코드의 시작과 끝을 msg명확하게 설명하기 때문입니다 ( msg +=한 줄마다 하나씩 비교하십시오.이 줄은 동일한 문자열에 추가된다는 추론 단계가 하나 더 필요합니다. +임의의 한 줄을 잊어 버리는 오타가 있습니까?).

이 방법과 관련하여 반복 본문 내에서 반복 및 검사를 사용하여 문자열을 작성해야하는 경우가 많으므로 함수 호출 내에 해당 부분을 추가하는 것은 옵션이 아닙니다.

가까운 대안은 다음과 같습니다.

msg = 'This message is so long, that it requires '
msg += 'many lines to write, one reason for that\n'
msg += 'is that it contains numbers, like this '
msg += 'one: ' + str(x) +', which take up more space\n'
msg += 'to insert. Note how newlines are also included '
msg += 'and can be better presented in the code itself.'
print(msg)

첫 번째가 바람직하지만.

다른 방법은 이전 방법과 비슷하지만 아래 줄에서 메시지를 시작합니다 print. 그 이유는 왼쪽에 공간을 확보하는 print(것입니다. 그렇지 않으면 자체가 오른쪽으로 "푸시"합니다. 이러한 들여 쓰기 소비는 메시지를 구성하는 나머지 행에 의해 상속되는데, PEP 8에 따르면 그것들은 print그 위에 있는 여는 괄호와 일치해야하기 때문 입니다. 따라서 메시지가 이미 길면 더 많은 행으로 전달되어야합니다.

대조:

raise TypeError('aaaaaaaaaaaaaaaa' +
                'aaaaaaaaaaaaaaaa' +
                'aaaaaaaaaaaaaaaa')

이것으로 (여기에서 제 안됨) :

raise TypeError(
    'aaaaaaaaaaaaaaaaaaaaaaaa' +
    'aaaaaaaaaaaaaaaaaaaaaaaa')

The line spread was reduced. Of course this last approach does no apply so much to print, because it is a short call. But it does apply to exceptions.

A variation you can have is:

raise TypeError((
    'aaaaaaaaaaaaaaaaaaaaaaaa'
    'aaaaaaaaaaaaaaaaaaaaaaaa'
    'aaaaa {x} aaaaa').format(x=x))

Notice how you don't need to have plus signs between pure strings. Also, the indentation guides the reader's eyes, no stray parentheses hanging below to the left. The replacements are very readable. In particular, such an approach makes writing code that generates code or mathematical formulas a very pleasant task.


You could use the following code where indentation doesn't matter:

>>> def fun():
        return ('{0} Here is a really long'
        ' sentence with {1}').format(3, 5)

You just need to enclose string in the parentheses.


You can use the fact that Python concatenates string literals which appear adjacent to each other:

>>> def fun():
...     print '{0} Here is a really long ' \
...           'sentence with {1}'.format(3, 5)

I'd probably split the long statement up into multiple shorter statements so that the program logic is separated from the definition of the long string:

>>> def fun():
...     format_string = '{0} Here is a really long ' \
...                     'sentence with {1}'
...     print format_string.format(3, 5)

If the string is only just too long and you choose a short variable name then by doing this you might even avoid having to split the string:

>>> def fun():
...     s = '{0} Here is a really long sentence with {1}'
...     print s.format(3, 5)

I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.

Note that these parens are not part of a method call — they're only implicit string literal concatenation.

Python 2:

def fun():
    print ('{0} Here is a really '
           'long sentence with {1}').format(3, 5)

Python 3 (with parens for print function):

def fun():
    print(('{0} Here is a really '
           'long sentence with {1}').format(3, 5))

Personally I think it's cleanest to separate concatenating the long string literal from printing it:

def fun():
    s = ('{0} Here is a really '
         'long sentence with {1}').format(3, 5)
    print(s)

참고URL : https://stackoverflow.com/questions/3346230/wrap-long-lines-in-python

반응형