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)

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