3 個值得使用的在 Python 3.1 中發(fā)布的特性
Python 3.1 于 2009 年首次發(fā)布,盡管它已經(jīng)發(fā)布了很長時間,但它引入的許多特性都沒有被充分利用,而且相當(dāng)酷。下面是其中的三個。
千位數(shù)格式化
在格式化大數(shù)時,通常是每三位數(shù)放置逗號,使數(shù)字更易讀(例如,1,048,576 比 1048576 更容易讀)。從 Python 3.1 開始,可以在使用字符串格式化函數(shù)時直接完成:
- "2 to the 20th power is {:,d}".format(2**20)
- '2 to the 20th power is 1,048,576'
,d 格式符表示數(shù)字必須用逗號格式化。
Counter 類
collections.Counter 類是標(biāo)準(zhǔn)庫模塊 collections 的一部分,是 Python 中的一個秘密超級武器。它經(jīng)常在 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)]
執(zhí)行軟件包
Python 允許使用 -m 標(biāo)志來從命令行執(zhí)行模塊。甚至一些標(biāo)準(zhǔn)庫模塊在被執(zhí)行時也會做一些有用的事情;例如,python -m cgi 是一個 CGI 腳本,用來調(diào)試網(wǎng)絡(luò)服務(wù)器的 CGI 配置。
然而,直到 Python 3.1,都不可能像這樣執(zhí)行 軟件包。從 Python 3.1 開始,python -m package 將執(zhí)行軟件包中的 __main__ 模塊。這是一個放調(diào)試腳本或命令的好地方,這些腳本主要是用工具執(zhí)行的,不需要很短。
Python 3.0 在 11 年前就已經(jīng)發(fā)布了,但是在這個版本中首次出現(xiàn)的一些功能是很酷的,而且沒有得到充分利用。如果你還沒使用,那么將它們添加到你的工具箱中。
via: https://opensource.com/article/21/5/python-31-features