Python的隐藏功能[已关闭]

2022-09-05 00:56:34

Python编程语言有哪些鲜为人知但有用的功能?

  • 尝试将答案限制在Python核心。
  • 每个答案一个功能。
  • 提供该功能的示例和简短描述,而不仅仅是指向文档的链接。
  • 使用标题作为第一行来标注要素。

答案的快速链接:


答案 1

链接比较运算符:

>>> x = 5
>>> 1 < x < 10
True
>>> 10 < x < 20 
False
>>> x < 10 < x*10 < 100
True
>>> 10 > x <= 9
True
>>> 5 == x > 4
True

如果你认为它正在做,它出来作为,然后比较,这也是,那么不,这真的不是发生的事情(见最后一个例子。它实际上被翻译成 和 ,但键入的次数更少,每个术语只评估一次。1 < xTrueTrue < 10True1 < x and x < 10x < 10 and 10 < x * 10 and x*10 < 100


答案 2

获取 python 正则表达式解析树以调试正则表达式。

正则表达式是python的一个很好的功能,但是调试它们可能是一种痛苦,而且很容易弄错正则表达式。

幸运的是,python可以通过将未记录的,实验性的隐藏标志(实际上是128)传递给来打印正则表达式解析树。re.DEBUGre.compile

>>> re.compile("^\[font(?:=(?P<size>[-+][0-9]{1,2}))?\](.*?)[/font]",
    re.DEBUG)
at at_beginning
literal 91
literal 102
literal 111
literal 110
literal 116
max_repeat 0 1
  subpattern None
    literal 61
    subpattern 1
      in
        literal 45
        literal 43
      max_repeat 1 2
        in
          range (48, 57)
literal 93
subpattern 2
  min_repeat 0 65535
    any None
in
  literal 47
  literal 102
  literal 111
  literal 110
  literal 116

一旦你理解了语法,你就可以发现你的错误。在那里,我们可以看到我忘了逃避.[][/font]

当然,您可以将其与所需的任何标志组合在一起,例如带注释的正则表达式:

>>> re.compile("""
 ^              # start of a line
 \[font         # the font tag
 (?:=(?P<size>  # optional [font=+size]
 [-+][0-9]{1,2} # size specification
 ))?
 \]             # end of tag
 (.*?)          # text between the tags
 \[/font\]      # end of the tag
 """, re.DEBUG|re.VERBOSE|re.DOTALL)