python - 有没有一种干净的方法可以在 Python 中编写多行字符串?

标签 python python-2.7

<分区>

这听起来像是一个初学者问题,但我从来没有成功地用 Python 以干净的方式编写长字符串。

以下是我列出的 4 种方法。在我看来,它们都不合适。

def useless_func():
    # WRONG WAY A : string_A displays well but breaks the 80 char max PEP 8 recommandation
    string_A = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."

    # WRONG WAY B : string_B will create unwanted spaces between word 'sed' and 'do' when printed
    string_B = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed\
        do eiusmod tempor incididunt ut labore et dolore magna aliqua."

    # WRONG WAY C : string_C displays well  but makes my code ugly because it breaks indentation
    string_C = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed\
do eiusmod tempor incididunt ut labore et dolore magna aliqua."

    # WRONG WAY D : string_D (triples quotes) has the same problem than string_B (unwanted spaces)
    string_D = '''Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed
        do eiusmod tempor incididunt ut labore et dolore magna aliqua.'''

我错过了什么吗?

最佳答案

我会选择:

def pr():
    # parentheses are for grouping and (as a bonus) for a pretty indentation
    s = ("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
         "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
    print s

引用informal introduction to Python :

Two string literals next to each other are automatically concatenated; the first line above could also have been written word = 'Help' 'A'; this only works with two literals, not with arbitrary string expressions.

>>> s = 'a' 'b'
>>> s
'ab'
>>> s = 'a''b' # space is not necessary
>>> s
'ab'

旁注:连接是在编译为字节码期间执行的:

>>> import dis
>>> dis.dis(pr)

 0 LOAD_CONST               1 ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')

可能这种连接传统来自 C:

// prints "hello world"
#include <stdio.h>

int main(int argc, char **argv) {
  printf("hello" " world");
  return 0;
}

关于python - 有没有一种干净的方法可以在 Python 中编写多行字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21554392/

相关文章:

python - WingIDE——Python 2 和 Python 3

python - 如何在交叉验证和 GridSearchCV 中实现 SMOTE

python - 通过理解避免将重复项插入 Python 列表

python - 导入错误 : No module named _sqlite3 (even after doing eveything)

python - 如何用蓝色为 RGB 图像着色?

python - 查找沿轴不包括零的 numpy 数组的最小值/最大值

python - 你如何在 libtorrent 中获得 torrent 的总大小?

python - matplotlib:直方图未显示

python scrapy动态选择xpaths和css

python - 使用带有 UTF-8 的 soup.get_text()