Python编程语言中有哪些鲜为人知但很有用的特性?

尽量将答案限制在Python核心。 每个回答一个特征。 给出一个例子和功能的简短描述,而不仅仅是文档链接。 使用标题作为第一行标记该特性。

快速链接到答案:

参数解包 牙套 链接比较运算符 修饰符 可变默认参数的陷阱/危险 描述符 字典默认的.get值 所以测试 省略切片语法 枚举 其他/ 函数作为iter()参数 生成器表达式 导入该 就地值交换 步进列表 __missing__物品 多行正则表达式 命名字符串格式化 嵌套的列表/生成器推导 运行时的新类型 .pth文件 ROT13编码 正则表达式调试 发送到发电机 交互式解释器中的制表符补全 三元表达式 试着/ / else除外 拆包+打印()函数 与声明


当前回答

乘以布尔值

我在web开发中经常做的一件事是可选地打印HTML参数。我们在其他语言中都见过这样的代码:

class='<% isSelected ? "selected" : "" %>'

在Python中,你可以乘以一个布尔值,它就会像你期望的那样:

class='<% "selected" * isSelected %>'

这是因为乘法将布尔值强制转换为整数(0表示False, 1表示True),在python中,将字符串乘以int将重复该字符串N次。

其他回答

Python的禅宗

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

激活IDE中接受它的自动完成(如IDLE, Editra, IEP),而不是做: “嗨”。(然后你按TAB键),你可以在IDE中作弊,只是制造 嗨。”(你可以看到,在开始的时候没有单引号)因为它只会跟着最新的标点符号,就像当你添加:并按enter,它直接添加了一个缩进,不知道它是否会改变,但它不再是一个提示:)

字典有一个get()方法

字典有一个'get()'方法。如果你执行d['key']而key不存在,你会得到一个异常。如果执行d.t get('key'),如果'key'不存在,则返回None。您可以添加第二个参数来返回该项,而不是None,例如:d.t get('key', 0)。

它非常适合做数字相加这样的事情:

Sum [value] = Sum。Get (value, 0) + 1

就地值交换

>>> a = 10
>>> b = 5
>>> a, b
(10, 5)

>>> a, b = b, a
>>> a, b
(5, 10)

赋值语句的右边是一个表达式,用于创建一个新的元组。赋值的左边立即将(未引用的)元组解包为名称a和b。

赋值之后,新的元组不被引用,并标记为垃圾收集,绑定到a和b的值已经交换。

正如Python教程中关于数据结构的部分所述,

注意,多重赋值实际上只是元组打包和序列解包的组合。

三元运算符

>>> 'ham' if True else 'spam'
'ham'
>>> 'ham' if False else 'spam'
'spam'

这是在2.5中添加的,在此之前你可以使用:

>>> True and 'ham' or 'spam'
'ham'
>>> False and 'ham' or 'spam'
'spam'

然而,如果你想要处理的值被认为是假的,有一个区别:

>>> [] if True else 'spam'
[]
>>> True and [] or 'spam'
'spam'