Programing

파이썬에서 줄 바꿈 (줄 연속)을 어떻게 할 수 있습니까?

lottogame 2020. 9. 28. 07:55
반응형

파이썬에서 줄 바꿈 (줄 연속)을 어떻게 할 수 있습니까?


여러 줄로 나누고 싶은 긴 코드 줄이 있습니다. 무엇을 사용하고 구문은 무엇입니까?

예를 들어 여러 문자열을 추가하면

e = 'a' + 'b' + 'c' + 'd'

다음과 같이 두 줄로 작성하십시오.

e = 'a' + 'b' +
    'c' + 'd'

라인은 무엇입니까? 문제없이 다음 줄에 인수를 가질 수 있습니다.

a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
            blahblah6, blahblah7)

그렇지 않으면 다음과 같이 할 수 있습니다.

if a == True and \
   b == False

자세한 내용 스타일 가이드확인하세요 .

예제 라인에서 :

a = '1' + '2' + '3' + \
    '4' + '5'

또는:

a = ('1' + '2' + '3' +
    '4' + '5')

스타일 가이드는 괄호와 함께 암시 적 연속을 사용하는 것이 선호되지만이 특별한 경우에는 표현식 주위에 괄호를 추가하는 것이 아마도 잘못된 방법이라고 말합니다.


에서 PEP 8 - 파이썬 코드에 대한 스타일 가이드 :

긴 줄을 감싸는 가장 좋은 방법은 괄호, 대괄호 및 중괄호 안에 Python의 암시 적 줄 연속을 사용하는 것입니다. 긴 줄은 괄호로 묶어 여러 줄로 나눌 수 있습니다. 줄 연속을 위해 백 슬래시를 사용하는 것보다 우선적으로 사용해야합니다.

때때로 백 슬래시는 여전히 적절할 수 있습니다. 예를 들어, 길고 여러 개의 with 문은 암시 적 연속을 사용할 수 없으므로 백 슬래시가 허용됩니다.

with open('/path/to/some/file/you/want/to/read') as file_1, \
        open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

또 다른 경우는 assert 문입니다.

계속되는 줄을 적절하게 들여 쓰기하십시오. 이항 연산자를 나누는 데 선호되는 위치 는 연산자 앞이 아니라 연산자 입니다. 몇 가지 예 :

class Rectangle(Blob):

    def __init__(self, width, height,
                 color='black', emphasis=None, highlight=0):
        if (width == 0 and height == 0 and
                color == 'red' and emphasis == 'strong' or
                highlight > 100):
            raise ValueError("sorry, you lose")
        if width == 0 and height == 0 and (color == 'red' or
                                           emphasis is None):
            raise ValueError("I don't think so -- values are %s, %s" %
                             (width, height))
        Blob.__init__(self, width, height,
                      color, emphasis, highlight)

이제 PEP8은 가독성을 높이기 위해 수학자 및 게시자가 사용 하는 반대 규칙 (이진 연산 중단)을 권장합니다 .

이항 연산자 앞에 Donald Knuth의 중단 스타일은 연산자를 수직으로 정렬하므로 어떤 항목을 더하고 빼는 지 결정할 때 눈의 부담이 줄어 듭니다.

에서 : PEP8 해야 전이나 이항 연산자 후 줄 바꿈? :

Donald Knuth는 그의 Computers and Typesetting 시리즈에서 전통적인 규칙에 대해 설명합니다. "단락 ​​내의 공식은 항상 이진 연산과 관계 후에 분리되지만 표시된 공식은 항상 이진 연산 전에 분리됩니다."[3]

수학의 전통을 따르면 일반적으로 더 읽기 쉬운 코드가 생성됩니다.

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.

[3]: Donald Knuth's The TeXBook, pages 195 and 196


The danger in using a backslash to end a line is that if whitespace is added after the backslash (which, of course, is very hard to see), the backslash is no longer doing what you thought it was.

See Python Idioms and Anti-Idioms (for Python 2 or Python 3) for more.


Put a \ at the end of your line or enclose the statement in parens ( .. ). From IBM:

b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))

or

b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)

You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \ to a line to explicitly break it:

x = (tuples_first_value,
     second_value)
y = 1 + \
    2

From the horse's mouth: Explicit line joining

Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

if 1900 < year < 2100 and 1 <= month <= 12 \
   and 1 <= day <= 31 and 0 <= hour < 24 \
   and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
        return 1

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.


It may not be the Pythonic way, but I generally use a list with the join function for writing a long string, like SQL queries:

query = " ".join([
    'SELECT * FROM "TableName"',
    'WHERE "SomeColumn1"=VALUE',
    'ORDER BY "SomeColumn2"',
    'LIMIT 5;'
])

Taken from The Hitchhiker's Guide to Python (Line Continuation):

When a logical line of code is longer than the accepted limit, you need to split it over multiple physical lines. The Python interpreter will join consecutive lines if the last character of the line is a backslash. This is helpful in some cases, but should usually be avoided because of its fragility: a white space added to the end of the line, after the backslash, will break the code and may have unexpected results.

A better solution is to use parentheses around your elements. Left with an unclosed parenthesis on an end-of-line the Python interpreter will join the next line until the parentheses are closed. The same behaviour holds for curly and square braces.

However, more often than not, having to split a long logical line is a sign that you are trying to do too many things at the same time, which may hinder readability.

Having that said, here's an example considering multiple imports (when exceeding line limits, defined on PEP-8), also applied to strings in general:

from app import (
    app, abort, make_response, redirect, render_template, request, session
)

참고URL : https://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python

반응형