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

当前回答

我使用递归函数来构建复杂的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查询。

其他回答

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

嗯。

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

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

就这样。

作为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()函数使用了原始字符串中的大括号。

你说的是多行字符串吗?简单,使用三引号开始和结束它们。

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

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

我个人认为,以下是用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变量替换。