我有一个很长的疑问。我想用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

当前回答

该方法使用:

使用三引号字符串几乎没有内部标点符号使用检查模块去除局部压痕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}'''
)

其他回答

该方法使用:

使用三引号字符串几乎没有内部标点符号使用检查模块去除局部压痕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}'''
)

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

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

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

我喜欢这种方法,因为它有阅读的特权。在我们有长串的情况下,没有办法!根据您所处的缩进级别,每行仍限于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
)
"""

嗯。

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

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

就这样。

结合以下观点:

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]的方式!”-。。。