1. 正则表达式 match 和 search 区别:
match从开始处匹配,search扫描整个字符串。
>>> regex=re.compile(r'hello')
>>> match=regex.match("world hello")
>>> print match
None
但是match换成search可以匹配。。
注意:
!!!只要有一部分匹配成功,match就不是 None,后续使用时需要判断 match.group() 与源字符串是否完全一致。否则可能只匹配了一部分。后面取各个 group 的时候会出错。
!!!判断完全一致的时候,要注意原始字符串有没有回车符啊!!要注意 line.strip('\n') 啊。
2. 原始字符串的用法:
>>> regex=re.compile('\bhello\b')
>>> match=regex.search("hello world")
>>> print match
None
之所以没有匹配是因为 \b 在 ASCII 码中表示退格符,
而在正则匹配中表示单词的边界。
两个含义产生冲突,会按照退格符匹配。所以需要两个\\。
>>> regex=re.compile('\\bhello\\b')
>>> match=regex.search("hello world")
>>> print match
<_sre.SRE_Match object at 0x77f920>
或者表达式前加字符 r,表示原始字符串。
>>> regex=re.compile(r'\bhello\b')
>>> match=regex.search("hello world")
>>> print match
<_sre.SRE_Match object at 0x77f988>
3.数据结构“dict”
如果key不在dict_a中,则
dict_a[key] += 3
是错误的。
但是可以这样写:
dict_a[key] = 3
所以此种情况可以用“=”不能用“+=”