小编典典

Python的隐藏功能

python

Python的隐藏功能


阅读 317

收藏
2020-02-10

共2个答案

小编典典

链接比较运算符:

>>> 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 < x,它显示为True,然后比较True < 10,它也是True,那么不,那实际上不是什么事情(请参阅最后一个示例。)它实际上是翻译成1 < x and x < 10,和x < 10 and 10 < x * 10 and x*10 < 100,但键入和每个输入较少该术语仅评估一次。

2020-02-10
小编典典

获取python regex解析树以调试你的regex

正则表达式是python的一个很棒的功能,但是调试它们可能会很麻烦,而且很容易使正则表达式出错。

幸运的是,python可以通过将未记录的,实验性的隐藏标志re.DEBUG(实际上是128个)传递给,从而输出正则表达式分析树re.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)
2020-02-10