2009-07-09 109 views
1

如何在代碼中分解長的一個班輪字符串,並讓字符串與其餘代碼一起縮進? PEP 8在這種情況下沒有任何示例。Python中冗長的單行字符串,不超過最大行長度

正確ouptut但奇怪的縮進:

if True: 
    print "long test long test long test long test long \ 
test long test long test long test long test long test" 

>>> long test long test long test long test long test long test long test long test long test long test 

壞輸出,但看起來在代碼更好:

if True: 
    print "long test long test long test long test long \ 
    test long test long test long test long test long test" 

>>> long test long test long test long test long  test long test long test long test long test long test 

哇,很多快速的答案。謝謝!

回答

6
if True: 
    print "long test long test long test long test long"\ 
    "test long test long test long test long test long test" 
27

相鄰的字符串是在編譯時串連:

if True: 
    print ("this is the first line of a very long string" 
      " this is the second line") 

輸出:

this is the first line of a very long string this is the second line 
+0

爲什麼這顯着更多投票? – JcMaco 2009-07-09 19:00:02

+1

最有可能是因爲它比當前接受的答案有更多的信息,並且因爲它更多是'Pythonic'(PEP 8:「包裝長行的首選方式是使用Python在括號,括號和大括號內的隱含行連續)。也可能有一些個人偏好,但作爲答案的作者,我不能對此發表評論。 – 2009-07-09 19:19:33

+0

@Noah,我再也不同意你了。我認爲它被接受的唯一原因是其最後一行對@ JcMaco原始文章的刪減之間的一致性。這是微不足道的,不令人信服。事實上,我也更喜歡PEP 8風格。對不起,昨晚我沒有補充任何補充信息,因爲我必須在那個時候睡覺,......我的英文破碎。 – sunqiang 2009-07-09 22:26:36

2

你可以用斜槓加入單獨字符串是這樣的:

if True: 
    print "long test long test long test long test long " \ 
      "test long test long test long test long test long test" 
-6
if True: 
    print "long test long test long test "+ 
    "long test long test long test "+ 
    "long test long test long test " 

依此類推。

0

爲什麼沒有人推薦三重引號?

print """ blah blah 
      blah ..............""" 
相關問題