这是关于 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's song 前八行中最常见的五个字母
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 脚本,用于调试 Web 服务器的 CGI 配置。
然而,在 Python 3.1 之前,不可能像这样执行包。从 Python 3.1 开始,python -m package
将执行包中的 __main__
模块。这是放置调试脚本或主要与工具一起执行且不需要简短的命令的好地方。
Python 3.0 是 11 年多前发布的,但此版本中首次出现的一些功能很酷且未被充分利用。如果您还没有这样做,请将它们添加到您的工具包中。
评论已关闭。