Python编程语言的哪些不太知名但有用的特性是什么?
快速链接到答案:
发布于 2008-09-19 13:47:15
链接比较运算符:
>>> 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,但是使用较少的输入,每个术语只进行一次评估。
发布于 2008-09-27 13:18:09
获得python解析树来调试regex.
正则表达式是python的一个很好的特性,但是调试它们可能会很痛苦,而且很容易出错。
幸运的是,python可以通过将未记录的、实验性的隐藏标志re.DEBUG (实际上是128个)传递给re.compile来打印regex解析树。
>>> 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]。
当然,您可以将它与您想要的任何标志结合起来,比如注释regexes:
>>> 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)发布于 2008-09-22 19:51:20
枚举
用枚举包一个可迭代的项,它将生成该项及其索引。
例如:
>>> a = ['a', 'b', 'c', 'd', 'e']
>>> for index, item in enumerate(a): print index, item
...
0 a
1 b
2 c
3 d
4 e
>>>参考文献:
https://stackoverflow.com/questions/101268
复制相似问题