3 個值得使用的在 Python 3.1 中發布的特性
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