创建长多行字符串的Pythonic方法

2024-03-19 03:14:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很长的问题。我想用Python把它分成几行。用JavaScript实现这一点的一种方法是使用几个句子,并用一个+操作符将它们连接起来(我知道,这可能不是最有效的方法,但我并不真正关心这个阶段的性能,只关心代码的可读性)。示例:

var long_string = 'some text not important. just garbage to' +
                  'illustrate my example';

我尝试在Python中做类似的事情,但是没有成功,所以我使用\来分割长字符串。但是,我不确定这是否是唯一的/最好的/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

Tags: and方法代码iddefasactionaccount
3条回答

\来断线对我很有用。下面是一个例子:

longStr = "This is a very long string " \
        "that I wrote to help somebody " \
        "who had a question about " \
        "writing long strings in 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语句中,多行字符串也可以。但是,如果多行字符串包含的额外空白是个问题,那么这将是实现您所需的一个好方法。

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

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

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

相关问题 更多 >