1. 程式人生 > >python 折行的正確姿勢

python 折行的正確姿勢

在寫 python 程式碼時,有時變數值是一個非常長的字串,比如這樣:

line = 'this is a very very very very very very very very very very long string'

如果寫在一行裡,難看不說,可能還過不了一些程式碼風格檢測。

那麼應該怎麼折行呢?

方案1

line = """
this is a very very very very
very very very very very very
very very very very very very
long string
"""

但是這個方案有個弊端,本來是一行字串,結果變成了多行,而且如果有縮排的話,本來表示縮排的空格,也作為字串的一部分了。跟我們實際想要的並不一致。

方案2

line = 'this is a\
very very very
long string 
'

此方案解決了方案1裡多餘的換行符的問題,字串真的是一行了。但是同樣沒解決縮排導致的多餘的空格的問題

方案3

line = (
    "this is a"
    "very very very very"
    "long string"
)

此方案完美地解決了長字串 折行/換行 的問題。
另外強調一下,如果有格式化字串需求的話,應該這麼寫:

a = "test_str"
b = 123
line = (
    "i have a string %s"
    "and a number %d"
) % (a, b)

媽媽再也不用擔心我的一行程式碼太長了