python - 如何将长字符串的定义拆分为多行?

标签 python string multiline multilinestring

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

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

我尝试在 Python 中做类似的事情,但没有成功,所以我使用 \ 来拆分长字符串。但是,我不确定这是否是唯一/最好/pythonicest 的方法。看起来很尴尬。 实际代码:

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

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

关于python - 如何将长字符串的定义拆分为多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10660435/

相关文章:

java - JButton 和 JField 标签/文本?

xcode - 在 Xcode 运行脚本 bin/sh 中使用 sed 查找和替换多行

python - 在 Python 中写入流式传输到 Google Cloud Storage

python - 从组中获取列描述

正则表达式匹配包含任意顺序的两个名称的字符串

python - 使用换句话说,格式化字符串的长度

python - 如何在python中找到另一个字符串(句子)中一个字符串(可以是多个单词)的计数/出现次数

python - 从 Python 文件中读取行的更好方法是什么?

python - 使用 Flask-Restful 返回呈现的模板在浏览器中显示 HTML

python - 分发用 Python 编写的程序