7:正则表达式
1:re模块match()函数尝试从字符串的开头开始对模式进行匹配,如果匹配成功,则匹配对象的group()方法可以用来显示成功的匹配,如果匹配失败,则显示none
2:re模块的search()函数从左到右搜索字符串出现的位置
match函数
import re
m=re.match('foo','seafood')
if m is not None:
print(m.group())
else:
print ('fail')
结果是fail
search函数
import re
m=re.search('foo','seafood')
if m is not None:
print(m.group())
else:
print ('fail')
结果是返回foo
文件读写
with方法可以自动调用close()方法
with open('/path/to/file', 'r') as f:
print(f.read())
open后面跟的是相对路径
如果读写方法是w,如果文件已经存在,则会覆盖原来的内容;如果文件不存在,则会创建一个
如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便:
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉