python入门备忘录

时间:2021-09-07 15:27:52

1,打开路径中包含中文的文件(解决中文乱码):

# -*- coding:utf-8 -*-

f = open('C:\Users\lanzao\Desktop\网易笔试.txt'.decode('utf-8'),'r+')
try:

cont = f.read()
print cont

finally:

f.close()


按行读取文件,不换行(去掉每行的\n):

for line in f:

line = line.strip('\n')

print line


2,将字符串a中的word替换为lanzao:

import re

a="hello,world"

print re.sub('wold','lanzao',a)