질문자 :Pablo Mescher
아주 긴 질문이 있습니다. 파이썬에서 여러 줄로 나누고 싶습니다. JavaScript에서 수행하는 방법은 여러 문장을 사용하고 +
연산자로 결합하는 것입니다(아마도 가장 효율적인 방법은 아니지만 이 단계에서 성능에 대해서는 크게 걱정하지 않고 코드 가독성만 고려하면 됩니다. ). 예시:
var long_string = 'some text not important. just garbage to' + 'illustrate my example';
Python에서 비슷한 작업을 시도했지만 작동하지 않아 \
를 사용하여 긴 문자열을 분할했습니다. 그러나 이것이 유일한/최고의/파이썬 방법인지 확실하지 않습니다. 어색해 보인다. 실제 코드:
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 ...'
마지막으로 Python에서 다음과 같이 긴 줄을 구성할 수도 있습니다.
s = ("this is a very" "long string too" "for sure ..." )
여기 에는 추가 공백이나 줄 바꿈이 포함되지 않습니다 (이는 공백 건너뛰기의 결과가 어떤 결과를 초래하는지 보여주는 의도적인 예입니다):
'this is a verylong string toofor sure ...'
쉼표가 필요하지 않습니다. 결합할 문자열을 한 쌍의 괄호에 넣고 필요한 공백과 줄 바꿈을 고려하십시오.
Levon여러 줄 문자열을 원하지 않고 긴 한 줄 문자열만 있으면 괄호를 사용할 수 있습니다. 문자열 세그먼트 사이에 쉼표를 포함하지 않도록 하십시오. 그러면 튜플이 됩니다.
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 문에서 여러 줄 문자열도 괜찮을 것입니다. 그러나 여러 줄 문자열에 포함된 추가 공백이 문제가 되는 경우 원하는 것을 달성하는 좋은 방법이 될 것입니다.
Jesse\
줄 바꿈은 저에게 효과적입니다. 다음은 예입니다.
longStr = "This is a very long string " \ "that I wrote to help somebody " \ "who had a question about " \ "writing long strings in Python"
amphibient나는 이것에 만족했습니다.
string = """This is a very long string, containing commas, that I split up for readability""".replace('\n',' ')
Eero Aaltonen긴 문자열을 작성할 때 일반적으로 SQL 쿼리 작성과 같은 작업을 수행하는 것으로 나타났습니다. 이 경우 가장 좋습니다.
query = ' '.join(( # Note double parentheses. 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
darkfeline이 접근 방식은 다음을 사용합니다.
- 삼중 따옴표로 묶인 문자열을 사용하여 내부 구두점이 거의 없음
-
inspect
모듈을 사용하여 로컬 들여쓰기를 제거합니다. -
account_id
및 def_id
변수에 Python 3.6 형식 문자열 보간('f')을 사용합니다.
이 방법이 가장 Pythonic하게 보입니다.
import inspect 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}''' )
Christopher Bruns""" 표기법을 사용할 때 변수를 포함할 수도 있습니다.
foo = '1234' long_string = """fosdl a sdlfklaskdf as as df ajsdfj asdfa sld a sdf alsdfl alsdfl """ + foo + """ aks asdkfkasdk fak"""
더 나은 방법은 명명된 매개변수와 .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)
gjgjgjPython >= 3.6에서는 형식화된 문자열 리터럴(f 문자열)을 사용할 수 있습니다.
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}'''
Vlad Bezden예를 들어:
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'"
pangpang여기에 설명된 대로 긴 문자열에 대해 textwrap.dedent
가 가장 적합합니다.
def create_snippet(): code_snippet = textwrap.dedent("""\ int main(int argc, char* argv[]) { return 0; } """) do_something(code_snippet)
fredrik다른 사람들은 이미 괄호 방법에 대해 언급했지만 괄호를 사용하여 인라인 주석이 허용된다는 점을 추가하고 싶습니다.
각 조각에 대한 설명:
nursery_rhyme = ( 'Mary had a little lamb,' # Comments are great! 'its fleece was white as snow.' 'And everywhere that Mary went,' 'her sheep would surely go.' # What a pesky sheep. )
계속 후 주석 허용되지 않음:
백슬래시 줄 연속( \
)을 사용할 때 주석은 허용되지 않습니다. SyntaxError: unexpected character after line continuation character
오류 이후에 예기치 않은 문자가 나타납니다.
nursery_rhyme = 'Mary had a little lamb,' \ # These comments 'its fleece was white as snow.' \ # are invalid! 'And everywhere that Mary went,' \ 'her sheep would surely go.' # => SyntaxError: unexpected character after line continuation character
Regex 문자열에 대한 더 나은 주석:
https://docs.python.org/3/library/re.html#re.VERBOSE 의 예를 기반으로 ,
a = re.compile( r'\d+' # the integral part r'\.' # the decimal point r'\d*' # some fractional digits )
# Using VERBOSE flag, IDE usually can't syntax highight the string comment. a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X)
ddrscott개인적으로 Python에서 원시 SQL 쿼리를 작성하는 가장 좋은(간단하고 안전하며 Pythonic) 방법은 다음과 같습니다. 특히 Python의 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
장점
- 깔끔하고 심플한 코드(Pythonic!)
- SQL 인젝션으로부터 안전
- Python 2 및 Python 3 모두와 호환 가능(결국 Pythonic임)
- 문자열 연결이 필요하지 않습니다.
- 각 줄의 맨 오른쪽 문자가 공백인지 확인할 필요가 없습니다.
단점
- 쿼리의 변수가
?
자리 표시자, 어떤 항목을 추적하기가 조금 어려울 수 있습니다 ?
쿼리에 많은 변수가 있을 때 파이썬 변수로 대체됩니다.
Faheel파이썬에서 긴 문자열에 대한 일반적인 접근 방식으로 삼중 따옴표, split
및 join
사용할 수 있습니다.
_str = ' '.join('''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.'''.split())
산출:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo.'
SQL 쿼리와 관련된 OP의 질문과 관련하여 아래 답변은 SQL 쿼리 작성에 대한 이러한 접근 방식의 정확성을 무시하고 추가 가져오기 없이 읽기 쉽고 미학적인 방식으로 긴 문자열을 작성하는 데만 중점을 둡니다. 또한 이에 수반되는 계산 부하도 무시합니다.
삼중 따옴표를 사용하여 길고 읽기 쉬운 문자열을 만든 다음 split()
을 사용하여 목록으로 분할하여 공백을 제거한 다음 ' '.join()
다시 결합합니다. format()
명령을 사용하여 변수를 삽입합니다.
account_id = 123 def_id = 321 _str = ''' 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 = {} ''' query = ' '.join(_str.split()).format(account_id, account_id, def_id)
생산:
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 = 123 AND record_def.account_id=123 AND def_id=321
이 접근 방식은 PEP 8 과 일치하지 않지만 때때로 유용합니다.
원래 문자열의 중괄호는 format() 함수에서 사용됩니다.
Rasmus Groth실제 코드가 작동하지 않아야 합니다. "줄" 끝에 공백이 없습니다(예: role.descr as roleFROM...
).
여러 줄 문자열에는 삼중 따옴표가 있습니다.
string = """line line2 line3"""
여기에는 줄 바꿈과 추가 공백이 포함되지만 SQL의 경우 문제가 되지 않습니다.
Karoly Horvathtl;dr: """\
및 """
를 사용하여 다음 과 같이 문자열을 래핑합니다.
string = """\ This is a long string spanning multiple lines. """
공식 Python 문서에서 :
문자열 리터럴은 여러 줄에 걸쳐 있을 수 있습니다. 한 가지 방법은 """...""" 또는 '''...'''와 같이 삼중 따옴표를 사용하는 것입니다. 줄 끝은 문자열에 자동으로 포함되지만 줄 끝에 \를 추가하여 이를 방지할 수 있습니다. 다음 예:
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
다음 출력을 생성합니다(초기 줄 바꿈은 포함되지 않음).
Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to
Flow나는 보통 다음과 같은 것을 사용합니다.
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())
Israel Barth Rubio이것과 같은 것을 시도하십시오. 이 형식과 마찬가지로 이 속성에 대해 성공적으로 문의한 것처럼 연속 행을 반환합니다.
"message": f'You have successfully inquired about ' f'{enquiring_property.title} Property owned by ' f'{enquiring_property.client}'
Kelvin OnkundiSQL 문을 별도의 파일 action.sql
에 배치하고 다음을 사용하여 .py 파일에 로드할 수도 있습니다.
with open('action.sql') as f: query = f.read()
따라서 SQL 문은 Python 코드에서 분리됩니다. Python에서 채워야 하는 매개변수가 SQL 문에 있는 경우 문자열 형식화(예: %s 또는 {field})를 사용할 수 있습니다.
mrijken"À la" Scala 방식(하지만 OP가 요구하는 가장 Pythonic 방식이라고 생각합니다):
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 | ',' ')`.
참고: "...템플릿" 사이의 흰색 선. 및 "또한 ..."은 |
.
victe아이디어 결합:
Levon 또는 Jesse , Faheel 및 ddrscott
내 형식 제안으로 쿼리를 다음과 같이 작성할 수 있습니다.
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 ) vars = (account_id, account_id, def_id) # A tuple of the query variables cursor.execute(query, vars) # Using Python's sqlite3 module
또는 좋아:
vars = [] 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 = ' vars.append(account_id) or '?' ' AND' ' record_def.account_id = ' vars.append(account_id) or '?' ' AND' ' def_id = ' vars.append(def_id) or '?' ) cursor.execute(query, tuple(vars)) # Using Python's sqlite3 module
이는 'IN' 및 'vars.extend(options) 또는 n_options(len(options))'와 함께 흥미로울 수 있습니다. 여기서:
def n_options(count): return '(' + ','.join(count*'?') + ')'
또는 darkfeline 의 힌트로 선행 공백과 구분 기호 및 명명된 자리 표시자에 대해 여전히 실수를 할 수 있습니다.
SPACE_SEP = ' ' COMMA_SEP = ', ' AND_SEP = ' AND ' query = SPACE_SEP.join(( 'SELECT', COMMA_SEP.join(( 'action.descr as "action"', 'role.id as role_id', 'role.descr as role', )), 'FROM', COMMA_SEP.join(( 'public.role_action_def', 'public.role', 'public.record_def', 'public.action', )), 'WHERE', AND_SEP.join(( 'role.id = role_action_def.role_id', 'record_def.id = role_action_def.def_id', 'action.id = role_action_def.action_id', 'role_action_def.account_id = :account_id', 'record_def.account_id = :account_id', 'def_id = :def_id', )), )) vars = {'account_id':account_id,'def_id':def_id} # A dictionary of the query variables cursor.execute(query, vars) # Using Python's sqlite3 module
Cursor.execute-function 문서를 참조하십시오.
"이것이 [가장 파이썬스러운] 방법입니다!" - ...
e.d.n.a코드(예: 변수)가 들여쓰기되고 출력 문자열이 한 줄로 되어 있어야 합니다(줄 바꿈 없음).
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
Eyal Levin재귀 함수를 사용하여 복잡한 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)
추신: 필요한 경우 SQL 쿼리를 인쇄하기 위해 멋진 python-sqlparse 라이브러리를 살펴보십시오.
Sandeepdict 내부에 긴 문자열을 정의 하고 개행을 유지하지만 공백을 생략하기 위해 다음과 같은 상수로 문자열을 정의했습니다.
LONG_STRING = \ """ This is a long sting that contains newlines. The newlines are important. """ my_dict = { 'foo': 'bar', 'string': LONG_STRING }
flix읽기 권한이 있기 때문에 이 접근 방식을 좋아합니다. 긴 문자열이 있는 경우에는 방법이 없습니다! 들여쓰기 수준에 따라 여전히 한 줄에 80자로 제한되어 있습니다... 음... 더 말할 필요가 없습니다.
내 생각에 Python 스타일 가이드는 여전히 매우 모호합니다. 나는 Eero Aaltonen 접근 방식을 취했습니다 . 왜냐하면 그것이 읽기와 상식을 우선시하기 때문입니다. 나는 스타일 가이드가 우리를 도와야 하며 우리의 삶을 엉망으로 만들지 않아야 한다는 것을 이해합니다.
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 ) """
Eduardo Lucio공식 Python 문서에서 :
문자열 리터럴은 여러 줄에 걸쳐 있을 수 있습니다. 한 가지 방법은 """...""" 또는 '''...'''와 같이 삼중 따옴표를 사용하는 것입니다. 줄 끝은 문자열에 자동으로 포함되지만 줄 끝에 \를 추가하여 이를 방지할 수 있습니다. 다음 예:
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
다음 출력을 생성합니다(초기 줄 바꿈은 포함되지 않음).
Flow일반적으로 여러 줄 주석/문자열에 대해 list
및 join
lines = list() lines.append('SELECT action.enter code here descr as "action", ') lines.append('role.id as role_id,') lines.append('role.descr as role') lines.append('FROM ') lines.append('public.role_action_def,') lines.append('public.role,') lines.append('public.record_def, ') lines.append('public.action') query = " ".join(lines)
\n
'(줄 바꿈) 또는 ' ,
'(쉼표) 또는 '와 같은 모든 문자열을 사용하여 이러한 모든 목록 요소를 결합할 수 있습니다.
'(우주).
paone출처 : http:www.stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string