有没有一种在Python中编写多行字符串的简洁方法?

时间:2014-02-04 13:51:59

标签: 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.'''

我错过了什么吗?

4 个答案:

答案 0 :(得分:13)

我会选择:

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

引用informal introduction to Python

  

自动连接两个彼此相邻的字符串文字;   上面的第一行也可以写成word ='Help''A';   这仅适用于两个文字,而不是任意字符串   表达式。

>>> 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;
}

答案 1 :(得分:5)

您可以尝试:

string = "sdfsdfsdfsdfsdf" \
         "sdfsdfsdfsdfs"

结果:

>>> string
'sdfsdfsdfsdfsdfsdfsdfsdfsdfs'

使用paranthesis而不是\可以达到同样的效果,正如@Nigel Tufnel在他的回答中提到的那样。

答案 2 :(得分:1)

使用双重或单一三重报价怎么样:

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

答案 3 :(得分:0)

我认为这可以归结为您获得多少屏幕空间。

您可以使用连接..

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