#1寻常方式python匹配字符串
In [1]: str1='imooc python'
In [2]: str1.find('i')
Out[2]: 0
In [4]: str1.find('z')
Out[4]: -1
In [6]: str1.startswith('i')
Out[6]: True
#2.正则表达式re的使用
import re
#匹配'imooc',re的compile方法生成一个pattern对象
pa=re.compile(r'imooc')
#调用pattern的方法match匹配字符串
#匹配的结果放在math的对象里面,用match的方法显示匹配的结果
ma=pa.match(str1)#返回math对象
ma.group()#匹配字符串的数据
ma.span()#匹配的数据区间
ma.groups()#匹配的元组
In [11]: pa=re.compile(r'Imooc python',re.I)
In [12]: pa
Out[12]: re.compile(r'Imooc python', re.IGNORECASE)#忽略大小写
In [22]: pa=re.compile(r'(imooc)',re.I)
In [23]: ma=pa.match(str1)
In [24]: print ma.groups()#返回一个元组
('imooc',)
In [30]: ma1=re.match(r'imooc','imooc python')#简便写法
In [31]: ma1.group()
Out[31]: 'imooc'
In [32]: ma1=re.match(r'imooc','Z')
In [33]: ma1.group()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-33-a04cfb428c99> in <module>()
----> 1 ma1.group()
AttributeError: 'NoneType' object has no attribute 'group'
In [34]: