有没有一种用python编写多行字符串的干净方法?

Is there a clean way to write multi-lines strings in Python?

本问题已经有最佳答案,请猛点这里访问。

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

下面是我列出的4种方法。我觉得他们都不好。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.'''

我错过什么了吗?


我会选择:

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

引用对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.

1
2
3
4
5
6
>>> s = 'a' 'b'
>>> s
'ab'
>>> s = 'a''b' # space is not necessary
>>> s
'ab'

附加说明:在编译到字节码的过程中执行串联:

1
2
3
4
>>> import dis
>>> dis.dis(pr)

 0 LOAD_CONST               1 ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')

可能这个串联传统来自C:

1
2
3
4
5
6
7
// prints"hello world"
#include <stdio.h>

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


你可以试试:

1
2
string ="sdfsdfsdfsdfsdf" \
        "sdfsdfsdfsdfs"

结果:

1
2
>>> string
'sdfsdfsdfsdfsdfsdfsdfsdfsdfs'

同样的效果也可以通过使用偏执代替\,正如他在回答中提到的@nigel tuffel。


使用双引号或单引号怎么样?

1
2
3
4
5
6
7
8
9
10
11
>>> string_A ="""Lorem ipsum dolor sit amet,
... this is also my content
... this is also my content
... this is also my content"""

>>>
>>> print string_A
Lorem ipsum dolor sit amet,
this is also my content
this is also my content
this is also my content
>>>

我认为归根结底就是你能得到多少屏幕房地产。

您可以使用串联。

1
2
string_a ="this is my content"
string_a +="this is also my content"