文章目录
Python编程语言的鲜为人知的但有用的功能是什么?
尝试限制Python核心的答案。
每个答案的一个功能
给出一个功能的例子和简短描述,而不仅仅是文档的链接。
使用标题作为第一行标记该功能。
Quick links to answers:
Chaining comparison operators:>>> 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&lt; x,它出现为True,然后比较True&lt; 10,它也是True,那么不会,那真的不会发生什么(参见最后一个例子)。它真的转化为1&lt; x和x < 10和x < 10和10 < x * 10和x *
10 < 100,但输入较少,每个术语只评估一次。
获取python正则表达式分析树来调试你的正则表达式。
正则表达式是python的一个重要特性,但是调试它们可能是一件痛苦的事情,而正则表达式很容易让错误发生。
幸运的是,python可以通过将未公开的实验性隐藏标志re.DEBUG(实际上是128)传递给re.compile来打印正则表达式分析树。
/ p>
>>> re.compile("^[font(?:=(?P[-+][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 # 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)
未经作者同意,本文严禁转载,违者必究!