나는 아주 긴 질의입니다. 몇 줄을 Python 이 분할하려면 싶다. 그렇게 할 수 있는 방법을 사용하여 JavaScript 에서 약간만이라도 여러 마디였나 결합하는 것을 수신기마다 '+' 연산자 (그러니까말이야, 아마 it& # 39, s not 가장 효과적인 방법은 그것을하지 하지만 I& # 39 m 이 단계에서 코드 가독성과 검사에 대해 우려하고 있는 별로, 성능, 그냥). 예:
var long_string = 'some text not important. just garbage to' +
'illustrate my example';
비슷한 일을 노력했다고 하지만, 저는 't work, 파이썬, # 39 didn& 사용되는 \' 보장-분리 긴 구체화하십시오. 그러나 이 경우 유일한 / best / 피토니체스트 I& # 39 m, 길이 그렇게 확실하지 않다. 좀 보입니다. 실제 코드:
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 명은 물론 dell. 시작과 끝) 와 마찬가지로 's' 결과 문자열 취급하는 다른 구체화하십시오.
I. e.,:
' 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 쿼리를 작성할 때, 당신은 일반적으로 구축과 같은 일을 하는 긴 문장열 인데, 이 경우 가장:
query = ' '.join(( # note double parens, join() takes an iterable
"SELECT foo",
"FROM bar",
"WHERE baz",
))
레본 제안됩니다 취약할 수 있지만, 어떤 것이 없다.
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"""
편집: 더 나은 방법을 찾을 수 있는 release. params) 및 스포르마 ():
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)
Python 에서 사용할 수 있습니다. = 3.6tb > [포맷되었는지 구체화하십시오 리터럴 (f 문자열)] [1]
query= 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]: https://docs.python.org/3.6/reference/lexical_analysis.html # f 문장열
이 방식을 사용하고.
-;;;; 그냥 < s> 피하기 위해 한 초기 linefeed< /s> 백슬래시
이 방법이 가장 파이썬 다는일은 보인다.
# 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}'''
)
예를 들면 다음과 같습니다.
sql = ("select field1, field2, field3, field4 "
"from table "
"where condition1={} "
"and condition2={}").format(1, 2)
Output: 'select field1, field2, field3, field4 from table
where condition1=1 and condition2=2'
값이 문자열으로 다음과 같은 조건, 할 수 있어야 합니다.
sql = ("select field1, field2, field3, field4 "
"from table "
"where condition1='{0}' "
"and condition2='{1}'").format('2016-10-12', '2017-10-12')
Output: "select field1, field2, field3, field4 from table where
condition1='2016-10-12' and condition2='2017-10-12'"
개인적으로 다음 찾을 수 있는 최고의 (simple, 안전하고, 파이썬) 방법을 쓸 경우, 특히 기초형상 SQL 쿼리를 사용하여 파이썬으로 Python& # 39 의 sqlite3 모듈에서는:
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 = ?
AND record_def.account_id = ?
AND def_id = ?
'''
vars = (account_id, account_id, def_id) # a tuple of query variables
cursor.execute(query, vars) # using Python's sqlite3 module
내가 찾을 ['테스트라이퍼드덴트'] (https://docs.python.org/2/library/textwrap.html) 에 설명됨 문장열 가장 오래 [here] (https://amir.rachum.com/blog/2018/06/23/python-multiline-idioms/):
def create_snippet():
code_snippet = textwrap.dedent("""\
int main(int argc, char* argv[]) {
return 0;
}
""")
do_something(code_snippet)
이미 언급한 바 있지만, 괄호 안에 있는 다른 방법을 통해 추가 설명 괄호 안에 있는 인라인 I&; d like to # 39 를 사용할 수 있습니다.
"'파이썬 nursery_rhyme = ( & # 39, 비행기, & # 39. # 주석은 엄청난거야!
& # 39, & # 39 메리, 그리고 그 모든 갔다.
) "'
백슬래시 선 사용할 때 연속 요청 ('\'), 주석 허용되지 않습니다. # 39, ll 'SyntaxError you& 받는다. 후에 예상치 못한 문자 행 계속 문자 '오류:.
"' nursery_rhyme = & # 39, 비행기, & # 39. # 이 설명은\
& # 39, & # 39 메리, 그리고 그 모든 갔다. \
"'
"' a = 레이콩필레 (
) "'
"'
a = 레이콩필레 (,, 이 경우 모든 부품을 r" " " \d # + . # 소수점 이하
"'
난 대개 이 같은 일이.
text = '''
This string was typed to be a demo
on how could we write a multi-line
text in Python.
'''
귀찮게 할 수 있는 빈 공간에 제거할 경우, 각 행은 다음과 같습니다.
text = '\n'.join(line.lstrip() for line in text.splitlines())
192 & # "; la". 스칼라 길 (그러나 파이썬 방법으로 가장 OQ 요구를 생각한다).
description = """
| The intention of this module is to provide a method to
| pass meta information in markdown_ header files for
| using it in jinja_ templates.
|
| Also, to provide a method to use markdown files as jinja
| templates. Maybe you prefer to see the code than
| to install it.""".replace('\n | \n','\n').replace(' | ',' ')
스케쳐내 없이, 그냥 str 이동줄 동일팔레트에 '\n' 최종 인수를 시작할 때 첫 번째 복귀시킴:
.replace('\n | ',' ')`.
참고: 백인 사이에 선을 " .templates."; 또한, ." 및 "; 이후 '공백' 합니다.
내가 사용하는 복잡한 SQL 구축하십시오 재귀 함수를 질의입니다. 이 기법은 일반적으로 사용할 수 있는 대형 문장열 구축을 위한 코드 가독성과 검사에 유지하면서.
# Utility function to recursively resolve SQL statements.
# CAUTION: Use this function carefully, Pass correct SQL parameters {},
# TODO: This should never happen but check for infinite loops
def resolveSQL(sql_seed, sqlparams):
sql = sql_seed % (sqlparams)
if sql == sql_seed:
return ' '.join([x.strip() for x in sql.split()])
else:
return resolveSQL(sql, sqlparams)
P. S. 이 멋진 보면 꽤 인쇄하십시오 필요한 경우 SQL 쿼리를 파이썬 자크 라파스 라이브러리를 가지고 있다. http://sqlparse.readthedocs.org/en/latest/api/ # 스크루파르세스포르마
내가 생각하기에 보다 쉽게 읽을 수 있는 또 다른 옵션은 코드 (에드그 가변으로) 는 밀어맞춤된 및 출력 문자열 있어야 할 때 한 라이너 (no 줄 바꿈):
def some_method():
long_string = """
a presumptuous long string
which looks a bit nicer
in a text editor when
written over multiple lines
""".strip('\n').replace('\n', ' ')
return long_string
"' 문자열 =\ " " ";; 이것은 긴 문자열 스패닝을 여러 줄. " " ";; "'
[공식 파이썬 문서용으로] 에서 (https://docs.python.org/3.7/tutorial/introduction.html # 문장열):
>. 리터럴 문자열 여러 줄로 확장될 수 있습니다. 한 가지 방법을 사용하고 있습니다. >. 트리플 인용: ,, " " " ." " ". 또는 & # 39, & # 39, & # 39, & # 39, & # 39 .& # 39;;). 줄이 자동으로 끝 >. 하지만 애태우면 구체화하십시오 포함된 추가함으로써 이를 방지할 수 있습니다. >. \ 줄의 끝에. 다음 예제에서는:
"' 보기인쇄 (" " "\;;; 사용법: 꼬추 [옵션]
>. (참고로, 초기 줄 바꿈 없는 다음 출력입니다 만듭니다. >. 포함).
"' 사용법: 꼬추 [옵션]
이 때문에 제가 좋아하는 외곽진입 권한을 판독값입니다. 우리는 오랫동안 문장열 경우에 방법이 없습니다! 아직 제한적인 수준에 따라 한 줄에 80 자 및 밀어맞춤 있습니다. 뭐. 다른 사항은요 말할 필요가 없다. 제가 보기에 모호한 파이썬 스타일입니까 안내선은 여전히 높다. 난 당시 @Eero 알토넨 외곽진입 때문에 권한을 판독값 및 상식. 스타일 안내선 도와야 하지 않고 우리와 우리의 삶을 엉망하지 한 것으로 안다. 감사합니다!
class ClassName():
def method_name():
if condition_0:
if condition_1:
if condition_2:
some_variable_0 =\
"""
some_js_func_call(
undefined,
{
'some_attr_0': 'value_0',
'some_attr_1': 'value_1',
'some_attr_2': '""" + some_variable_1 + """'
},
undefined,
undefined,
true
)
"""