[python] 긴 여러 줄 문자열을 만드는 Pythonic 방법

매우 긴 쿼리가 있습니다. 파이썬에서 여러 줄로 나누고 싶습니다. JavaScript 로하는 방법은 여러 문장을 사용하고 +연산자 와 결합하는 것입니다 (아마도 가장 효율적인 방법은 아니지만이 단계의 성능에 대해서는 신경 쓰지 않습니다. 코드 가독성 만) . 예:

var long_string = 'some text not important. just garbage to' +
                  'illustrate my example';

파이썬에서 비슷한 것을 시도했지만 작동하지 않았으므로 \긴 문자열을 분할하는 데 사용 되었습니다. 그러나 이것이 유일하고 / 최고의 / 최신적인 방법인지 확실하지 않습니다. 어색해 보인다. 실제 코드 :

query = 'SELECT action.descr as "action", '\
    'role.id as role_id,'\
    'role.descr as role'\
    'FROM '\
    'public.role_action_def,'\
    'public.role,'\
    'public.record_def, '\
    'public.action'\
    'WHERE role.id = role_action_def.role_id AND'\
    'record_def.id = role_action_def.def_id AND'\
    'action.id = role_action_def.action_id AND'\
    'role_action_def.account_id = ' + account_id + ' AND'\
    'record_def.account_id=' + account_id + ' AND'\
    'def_id=' + def_id



답변

여러 줄 문자열에 대해 이야기하고 있습니까? 쉽게 시작하고 끝내려면 삼중 따옴표를 사용하십시오.

s = """ this is a very
        long string if I had the
        energy to type more and more ..."""

작은 따옴표 (물론 시작과 끝에 3 개)도 사용할 수 있으며 결과 문자열을 s다른 문자열 과 동일하게 처리 할 수 있습니다.

참고 : 문자열과 마찬가지로 시작 따옴표와 끝 따옴표 사이의 문자열이 문자열의 일부가되므로이 예제에는 선행 공백이 있습니다 (@ root45로 표시). 이 문자열에는 공백과 줄 바꿈이 모두 포함됩니다.

즉,

' this is a very\n        long string if I had the\n        energy to type more and more ...'

마지막으로 파이썬에서 다음과 같이 긴 줄을 만들 수도 있습니다.

 s = ("this is a very"
      "long string too"
      "for sure ..."
     )

여기 에는 여분의 공백이나 줄 바꿈이 포함 되지 않습니다 (공백을 건너 뛰면 어떤 결과가 나오는지 보여주는 의도적 인 예입니다).

'this is a verylong string toofor sure ...'

쉼표가 필요하지 않습니다. 간단히 문자열을 한 쌍의 괄호로 묶고 필요한 공백과 줄 바꿈을 고려해야합니다.


답변

여러 줄 문자열을 원하지 않고 긴 한 줄 문자열 만있는 경우 괄호를 사용할 수 있습니다. 문자열 세그먼트 사이에 쉼표를 포함시키지 않으면 튜플이됩니다.

query = ('SELECT   action.descr as "action", '
         'role.id as role_id,'
         'role.descr as role'
         ' FROM '
         'public.role_action_def,'
         'public.role,'
         'public.record_def, '
         'public.action'
         ' WHERE role.id = role_action_def.role_id AND'
         ' record_def.id = role_action_def.def_id AND'
         ' action.id = role_action_def.action_id AND'
         ' role_action_def.account_id = '+account_id+' AND'
         ' record_def.account_id='+account_id+' AND'
         ' def_id='+def_id)

구성하는 것과 같은 SQL 문에서 여러 줄 문자열도 좋습니다. 그러나 여러 줄 문자열에 포함 된 여분의 공백이 문제가 될 경우 원하는 것을 달성하는 좋은 방법입니다.


답변

\나를 위해 일 함으로써 줄을 끊는 것. 예를 들면 다음과 같습니다.

longStr = "This is a very long string " \
        "that I wrote to help somebody " \
        "who had a question about " \
        "writing long strings in Python"


답변

나는 이것에 만족했다.

string = """This is a
very long string,
containing commas,
that I split up
for readability""".replace('\n',' ')


답변

긴 문자열을 만들 때 일반적으로 SQL 쿼리 작성과 같은 작업을 수행하는 것이 좋습니다.이 경우 가장 좋습니다.

query = ' '.join((  # note double parens, join() takes an iterable
    "SELECT foo",
    "FROM bar",
    "WHERE baz",
))

Levon이 제안한 것은 좋지만 실수에 취약 할 수 있습니다.

query = (
    "SELECT foo"
    "FROM bar"
    "WHERE baz"
)

query == "SELECT fooFROM barWHERE baz"  # probably not what you want


답변

“” “표기법을 사용할 때 변수를 연결할 수도 있습니다.

foo = '1234'

long_string = """fosdl a sdlfklaskdf as
as df ajsdfj asdfa sld
a sdf alsdfl alsdfl """ +  foo + """ aks
asdkfkasdk fak"""

편집 : 이름이 params 및 .format () 인 더 나은 방법을 찾았습니다.

body = """
<html>
<head>
</head>
<body>
    <p>Lorem ipsum.</p>
    <dl>
        <dt>Asdf:</dt>     <dd><a href="{link}">{name}</a></dd>
    </dl>
    </body>
</html>
""".format(
    link='http://www.asdf.com',
    name='Asdf',
)

print(body)


답변

이 방법은 다음을 사용합니다.

  • 초기 줄 바꿈을 피하기 위해 백 슬래시 하나만
  • 삼중 따옴표로 묶인 문자열을 사용하여 내부 구두점이 거의 없음
  • 텍스트 랩을 사용하여 로컬 들여 쓰기를 제거합니다 . inspect 모듈을 합니다.
  • account_iddef_id변수에 파이썬 3.6 형식의 문자열 보간 ( ‘f’)을 사용합니다 .

이 방법은 나에게 가장 파이썬처럼 보입니다.

# import textwrap  # See update to answer below
import inspect

# query = textwrap.dedent(f'''\
query = inspect.cleandoc(f'''
    SELECT action.descr as "action",
    role.id as role_id,
    role.descr as role
    FROM
    public.role_action_def,
    public.role,
    public.record_def,
    public.action
    WHERE role.id = role_action_def.role_id AND
    record_def.id = role_action_def.def_id AND
    action.id = role_action_def.action_id AND
    role_action_def.account_id = {account_id} AND
    record_def.account_id={account_id} AND
    def_id={def_id}'''
)

업데이트 : 1/29/2019 @ShadowRanger의 제안 inspect.cleandoc대신 사용 제안textwrap.dedent