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

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay