Linux中國

3 個值得使用的在 Python 3.1 中發布的特性

這是 Python 3.x 首發特性系列文章的第二篇。Python 3.1 於 2009 年首次發布,儘管它已經發布了很長時間,但它引入的許多特性都沒有被充分利用,而且相當酷。下面是其中的三個。

千位數格式化

在格式化大數時,通常是每三位數放置逗號,使數字更易讀(例如,1,048,576 比 1048576 更容易讀)。從 Python 3.1 開始,可以在使用字元串格式化函數時直接完成:

"2 to the 20th power is {:,d}".format(2**20)
'2 to the 20th power is 1,048,576'

,d 格式符表示數字必須用逗號格式化。

Counter 類

collections.Counter 類是標準庫模塊 collections 的一部分,是 Python 中的一個秘密超級武器。它經常在 Python 的面試題的簡單解答中首次遇到,但它的價值並不限於此。

例如,在 Humpty Dumpty 的歌 的前八行中找出五個最常見的字母:

hd_song = """
In winter, when the fields are white,
I sing this song for your delight.

In Spring, when woods are getting green,
I'll try and tell you what I mean.

In Summer, when the days are long,
Perhaps you'll understand the song.

In Autumn, when the leaves are brown,
Take pen and ink, and write it down.
"""
import collections

collections.Counter(hd_song.lower().replace(' ', '')).most_common(5)
[('e', 29), ('n', 27), ('i', 18), ('t', 18), ('r', 15)]

執行軟體包

Python 允許使用 -m 標誌來從命令行執行模塊。甚至一些標準庫模塊在被執行時也會做一些有用的事情;例如,python -m cgi 是一個 CGI 腳本,用來調試網路伺服器的 CGI 配置。

然而,直到 Python 3.1,都不可能像這樣執行 軟體包。從 Python 3.1 開始,python -m package 將執行軟體包中的 __main__ 模塊。這是一個放調試腳本或命令的好地方,這些腳本主要是用工具執行的,不需要很短。

Python 3.0 在 11 年前就已經發布了,但是在這個版本中首次出現的一些功能是很酷的,而且沒有得到充分利用。如果你還沒使用,那麼將它們添加到你的工具箱中。

via: https://opensource.com/article/21/5/python-31-features

作者:Moshe Zadka 選題:lujun9972 譯者:geekpi 校對:wxy

本文由 LCTT 原創編譯,Linux中國 榮譽推出


本文轉載來自 Linux 中國: https://github.com/Linux-CN/archive

對這篇文章感覺如何?

太棒了
0
不錯
0
愛死了
0
不太好
0
感覺很糟
0
雨落清風。心向陽

    You may also like

    Leave a reply

    您的電子郵箱地址不會被公開。 必填項已用 * 標註

    此站點使用Akismet來減少垃圾評論。了解我們如何處理您的評論數據

    More in:Linux中國