2011-03-25 56 views
116

爲了服從python樣式規則,我將編輯器設置爲最多79列。Python風格 - 字符串延續?

在PEP中,它建議在括號,圓括號和大括號中使用python的隱含延續。但是,當我遇到字符串限制時處理字符串時,會變得有點奇怪。

例如,試圖用一個多

mystr = """Why, hello there 
wonderful stackoverflow people!""" 

將返回

"Why, hello there\nwonderful stackoverflow people!" 

這工作:

mystr = "Why, hello there \ 
wonderful stackoverflow people!" 

因爲它返回:

"Why, hello there wonderful stackoverflow people!" 

但是,當語句中縮進幾個街區,這看起來奇怪:

do stuff: 
    and more stuff: 
     and even some more stuff: 
      mystr = "Why, hello there \ 
wonderful stackoverflow people!" 

如果你試圖縮進第二行:

do stuff: 
    and more stuff: 
     and even some more stuff: 
      mystr = "Why, hello there \ 
      wonderful stackoverflow people!" 

你的字符串結束爲:

"Why, hello there    wonderful stackoverflow people!" 

我發現解決這個問題的唯一方法是:

do stuff: 
    and more stuff: 
     and even some more stuff: 
      mystr = "Why, hello there" \ 
      "wonderful stackoverflow people!" 

我喜歡哪一種更好,但眼睛也有點不安,因爲它看起來像是坐在無處不在的中間。這將產生正確的:

"Why, hello there wonderful stackoverflow people!" 

所以,我的問題是 - 什麼是不顯示我應該怎麼做這個有些人對如何做到這一點,是有什麼我失蹤的風格指南中的建議?

謝謝。

+1

高縮進級別也可能是你需要重構代碼,以便它更模塊化 – Daenyth 2011-03-25 20:18:38

+5

我縮進那麼多做出點的標誌。但是要意識到,至少可以達到第三級縮進是很容易的,但是即使只有一個縮進級別,標準方法也會使字符串變得非常不合適。 – sjmh 2011-03-25 20:30:35

+0

可能重複的[在Python中換行長行](http://stackoverflow.com/questions/3346230/wrap-long-lines-in-python) – JrBenito 2016-09-27 19:18:06

回答

172

由於adjacent string literals are automatically joint into a single string,你可以用括號內的隱含續行所推薦的PEP 8:

print("Why, hello there wonderful " 
     "stackoverflow people!") 
+1

謝謝Sven,我比我使用的風格多一點。 – sjmh 2011-03-25 20:34:42

+1

我認爲這只是一個竅門,但在閱讀python文檔後,我必須說,這很整齊。謝謝 ! – Medorator 2014-02-07 07:41:17

2

我解決此得到與

mystr = ' '.join(
     ["Why, hello there", 
     "wonderful stackoverflow people!"]) 
過去

。這並不完美,但對於需要在其中沒有換行符的非常長的字符串來說,它非常適用。

+12

在我的機器上,這需要350納秒,加入一個元組而不是列表需要250納秒。另一方面,隱式加入只需要25ns。隱性加入在簡單性和速度方面都是明顯的贏家。 – endolith 2012-08-22 01:09:58

+6

@ endolith:我同意使用圓括號更好,因爲它更乾淨,但這不是考慮性能的地方。如果您在運行時關心100 ns的差異,特別是在連接硬編碼字符串時,會出現問題。 – nmichaels 2012-08-27 13:51:35

+0

如果不知道背景,我不會說關心100ns是錯誤的。如果發生了一百萬次操作會怎麼樣? – Medorator 2014-02-07 07:42:45

18

只是指出,這是使用括號調用自動拼接。這很好,如果你碰巧已經在聲明中使用它們。否則,我只會使用'\'而不是插入括號(這是大多數IDE爲您自動執行的操作)。縮進應該對齊字符串延續,以便符合PEP8。例如:

my_string = "The quick brown dog " \ 
      "jumped over the lazy fox" 
2

另一種可能性是使用textwrap模塊。這也避免了問題中提到的「串在一起」的問題。

import textwrap 
mystr = """\ 
     Why, hello there 
     wonderful stackoverfow people""" 
print (textwrap.fill(textwrap.dedent(mystr)))