Python 3.1 中你应该在 2021 年使用的 3 个特性

探索一些未被充分利用但仍然有用的 Python 特性。
53 位读者喜欢这篇文章。
Python programming language logo with question marks

Opensource.com

这是关于 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 年多前发布的,但此版本中首次出现的一些功能很酷且未被充分利用。如果您还没有这样做,请将它们添加到您的工具包中。

接下来阅读
标签
Moshe sitting down, head slightly to the side. His t-shirt has Guardians of the Galaxy silhoutes against a background of sound visualization bars.
自 1998 年以来,Moshe 一直参与 Linux 社区,并在 Linux “安装聚会”中提供帮助。自 1999 年以来,他一直在编写 Python 程序,并为核心 Python 解释器做出了贡献。自从 DevOps/SRE 这些术语出现之前,Moshe 就一直担任 DevOps/SRE,他非常关心软件可靠性、构建可重现性以及其他此类事情。

评论已关闭。

Creative Commons License本作品根据 Creative Commons License 许可发布,但可能并非在所有情况下都能做到。您有责任确保您拥有重用本网站上任何作品的必要权限。Red Hat 和 Red Hat 徽标是 Red Hat, Inc. 在美国和其他国家/地区的注册商标。
© . All rights reserved.