3 个值得使用的在 Python 3.1 中发布的特性

开发 前端
Python 3.1 于 2009 年首次发布,尽管它已经发布了很长时间,但它引入的许多特性都没有被充分利用,而且相当酷。下面是其中的三个。

Python 3.1 于 2009 年首次发布,尽管它已经发布了很长时间,但它引入的许多特性都没有被充分利用,而且相当酷。下面是其中的三个。

千位数格式化

在格式化大数时,通常是每三位数放置逗号,使数字更易读(例如,1,048,576 比 1048576 更容易读)。从 Python 3.1 开始,可以在使用字符串格式化函数时直接完成:

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

,d 格式符表示数字必须用逗号格式化。

Counter 类

collections.Counter 类是标准库模块 collections 的一部分,是 Python 中的一个秘密超级武器。它经常在 Python 的面试题的简单解答中首次遇到,但它的价值并不限于此。

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

  1. hd_song = ""
  2. In winter, when the fields are white, 
  3. I sing this song for your delight. 
  4. In Spring, when woods are getting green, 
  5. I'll try and tell you what I mean. 
  6. In Summer, when the days are long, 
  7. Perhaps you'll understand the song. 
  8. In Autumn, when the leaves are brown, 
  9. Take pen and ink, and write it down. 
  10. """ 
  1. import collections 
  2. collections.Counter(hd_song.lower().replace(' ', '')).most_common(5) 
  1. [('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

 

责任编辑:赵宁宁 来源: Linux中国
相关推荐

2021-05-20 10:42:59

PythonPython 3.0编程语言

2020-07-14 08:45:13

Flink特性jira

2009-02-04 17:33:24

ibmdwPython

2021-03-09 11:20:35

Linux终端

2009-06-15 14:53:00

NetBeans 6.

2021-05-29 07:35:13

Python编程语言

2013-06-30 09:51:54

SpringWeb服务器

2011-02-25 10:00:04

Windows 8

2021-05-12 10:25:29

开发技能代码

2017-03-13 15:27:55

CSS新特性

2010-05-13 16:39:27

Subversion1

2012-06-13 10:26:21

iOS 6

2020-03-01 14:57:47

Python编程函数

2019-09-20 08:47:51

微信表情小程序

2020-12-09 11:52:28

Python字符串代码

2018-03-26 09:19:44

JavaScript开发 特性

2021-05-12 10:25:53

组件验证漏洞

2010-07-27 09:37:44

Flex

2023-06-19 10:30:04

Python工具数据科学工具

2024-01-15 00:30:04

Python 3语言版本
点赞
收藏

51CTO技术栈公众号