DEV Community

codemee
codemee

Posted on • Edited on

4 2

讓 Python 程式折行的方法

你一定有遇過幫物件取了很棒的名字, 具有說明意義, 一看就懂, 但唯一的問題就是名字可能很長, 例如以下這幾個一看就懂的名字:

>>> long_name = 10
>>> long_long_name = 20
>>> long_long_long_name = 3
Enter fullscreen mode Exit fullscreen mode

這些名字看起來很棒, 可是當你要用在運算式中時, 就可能會變這樣:

>>> a = long_name + long_long_name + long_long_long_name
>>>
Enter fullscreen mode Exit fullscreen mode

如果你很討厭這麼長的運算式, 也可以用脫義字元來取消斷行, 像是這樣:

>>> a = long_name + \
... long_long_name + \
... long_long_long_name
>>>
Enter fullscreen mode Exit fullscreen mode

但是這一個個的脫義字元實在很醜, 這時我們就可以藉助小括號:

>>> a = ( long_name +
...     long_long_name +
...     long_long_long_name
... )
>>>
Enter fullscreen mode Exit fullscreen mode

愛怎麼寫就怎麼寫:

>>> a = (
...     long_name
...     + long_long_name
...     + long_long_long_name
... )
>>>
Enter fullscreen mode Exit fullscreen mode

這是因為配對的括號內可以加入斷行, Python 會自動將成對的小括號內的內容接起來, 因此就可以善用小括號來幫助我們將程式碼排成適合閱讀的形式。當然, 你也可以回頭檢視一下物件名稱是不是取得過頭了, 也是改用縮寫、換個單字就會變短了, 但如果實在無法割捨, 本文介紹的方法就可以派上用場了。

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay