我有一个很长的疑问。我想用Python将它分成几行。在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个引号),并像对待任何其他字符串一样对待生成的字符串。

注意:与任何字符串一样,起始引号和结束引号之间的任何内容都将成为字符串的一部分,因此本示例有一个前导空格(如@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 ...'

不需要逗号,只需将要连接在一起的字符串放入一对括号中,并确保考虑到任何需要的空格和换行符。


你的实际代码不应该工作;在“行”的末尾缺少空格(例如,role.descr作为roleFROM…)。

多行字符串有三个引号:

string = """line
  line2
  line3"""

它将包含换行符和额外的空格,但对于SQL来说这不是问题。


如果不需要多行字符串,而只需要一个长的单行字符串,则可以使用括号。只需确保字符串段之间不包含逗号(那么它将是一个元组)。

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语句中,多行字符串也可以。但是,如果多行字符串包含的额外空白是一个问题,那么这将是一个实现您所需功能的好方法。

如注释中所述,以这种方式连接SQL查询是SQL注入安全风险,因此请使用数据库的参数化查询功能来防止这种情况发生。然而,我保留了答案,因为它直接回答了问题。


您还可以将SQL语句放置在单独的文件action.SQL中,并使用以下命令将其加载到.py文件中:

with open('action.sql') as f:
   query = f.read()

因此,SQL语句将与Python代码分离。如果SQL语句中有需要从Python填充的参数,则可以使用字符串格式(如%s或{field})。


我发现自己对这个很满意:

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

我发现,当构建长字符串时,您通常会做一些类似于构建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

用\换行对我很有用。下面是一个例子:

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

我使用递归函数来构建复杂的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.:看看很棒的python-sqlparse库,如果需要,可以打印SQL查询。


使用“”符号时,还可以包含变量:

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)

例如:

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'"

我认为当代码(例如,变量)缩进并且输出字符串应该是单行(没有换行)时,另一个选项更可读:

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

“la”Scala方式(但我认为这是OP要求的最具Python风格的方式):

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.”和“另外,…”之间的白线需要在|后面加一个空格。


在Python>=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}'''

我喜欢这种方法,因为它有阅读的特权。在我们有长串的情况下,没有办法!根据您所处的缩进级别,每行仍限于80个字符。。。好没必要说别的

在我看来,Python风格指南仍然非常模糊。我采用了埃罗·奥尔顿的方法,因为它有利于阅读和常识。我明白,风格指南应该帮助我们,而不是让我们的生活一团糟。

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
)
"""

我个人认为,以下是用Python编写原始SQL查询的最佳(简单、安全和Python化)方法,尤其是在使用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

Pros

整洁而简单的代码(Pythonic!)避免SQL注入与Python 2和Python 3兼容(毕竟是Pythonic)不需要字符串串联无需确保每行最右边的字符是空格

Cons

由于查询中的变量被替换为?占位符,它可能会变得有点难以跟踪哪个?当查询中有很多Python变量时,将由哪个Python变量替换。


该方法使用:

使用三引号字符串几乎没有内部标点符号使用检查模块去除局部压痕account_id和def_id变量使用Python 3.6格式的字符串插值('f')。

这种方式在我看来是最有蟒蛇风格的。

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}'''
)

我通常用这样的词:

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())

我发现textwrap.dedent最适合长字符串,如下所述:

def create_snippet():
    code_snippet = textwrap.dedent("""\
        int main(int argc, char* argv[]) {
            return 0;
        }
    """)
    do_something(code_snippet)

通常,我对多行注释/string使用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”(换行符)或“,”(逗号)或“”(空格)。


其他人已经提到了圆括号方法,但我想补充一点,使用圆括号时,允许内联注释。

对每个片段的注释:

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:一行接一行的连续字符错误。

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)

试试这样的。类似于此格式,它将向您返回一条连续的行,就像您已成功询问此属性:

"message": f'You have successfully inquired about '
           f'{enquiring_property.title} Property owned by '
           f'{enquiring_property.client}'

tl;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

从Python官方文档中:

字符串文本可以跨越多行。一种方法是使用三引号:“”“…”“”或“”“”…“”。行的结束是自动的包含在字符串中,但可以通过添加\在线路的末端。以下示例:

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

生成以下输出(注意,初始换行符不是包括在内):


为了在字典内定义长字符串,保留换行符但省略空格,我最终以如下常量定义字符串:

LONG_STRING = \
"""
This is a long sting
that contains newlines.
The newlines are important.
"""

my_dict = {
   'foo': 'bar',
   'string': LONG_STRING
}

作为Python中长字符串的一般方法,可以使用三引号、拆分和连接:

_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.'

关于OP关于SQL查询的问题,下面的答案忽略了这种构建SQL查询方法的正确性,只关注于以可读和美观的方式构建长字符串,而不需要额外的导入。它也忽略了这带来的计算负载。

使用三重引号,我们构建了一个长且可读的字符串,然后使用split()将其分解为一个列表,从而剥离空白,然后使用“”.jjoin()将它连接起来。最后,我们使用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

这种方法不符合PEP8,但我发现它有时很有用。

请注意,format()函数使用了原始字符串中的大括号。


结合以下观点:

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(option))”一起使用可能很有趣,其中:

def n_options(count):
    return '(' + ','.join(count*'?') + ')'

或者从darkcaline那里得到的提示是,您可能仍然会在使用前导空格和分隔符以及命名占位符时出错:

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的文档。

“这是[最Python]的方式!”-。。。


添加@Levon的答案。。。。

1.创建如下多行字符串:

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

print(paragraph)

输出:

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

此字符串将包含换行符和空格。因此,请移除它们。

2.使用正则表达式删除多余的空格

paragraph = re.sub('\s+', ' ', paragraph)
print(paragraph)

输出:

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

我知道这是一个相当古老的问题,但Python在此期间发生了变化,我看不到这个答案,所以我们开始。

另一种方法是使用\剪切当前行并移动到另一行:

print("This line will \
get carried over to\
 the new line.\
Notice how this\
word will be together because \
of no space around it")

嗯。

我知道这个问题发布已经很久了。但我刚刚找到了我想用来为项目中的变量分配长字符串和多行字符串的样式。这需要一点额外的运行时间,但仍然保留了代码的美感,即使我将字符串分配给的变量缩进很大。

    # Suppose the following code is heavily indented
    line3header = "Third"

    variable = fr"""

First line.
Second line.
{line3header} line.
{{}} line.
...
The last line.

    """.strip()
    """A variable whose name is Variable.

    You can even add a docstring here.
    """

    variable = variable.format("Fourth")
    print(variable)
    variable += "\n"
    print(variable, end="")

就这样。


PEP 8风格指南建议使用括号:

包装长行的首选方式是在括号、括号和大括号内使用Python的隐含行延续。通过将表达式括在括号中,可以在多行上打断长行。应优先使用这些字符,而不是使用反斜杠作为换行符。

例子:

long_string = (
    "This is a lengthy string that takes up a lot of space. I am going to "
    "keep on typing words to fill up more and more space to show how you can "
    "split the string across multiple lines."
)