Python字符串替换

来源:互联网 发布:垂直同步 知乎 编辑:程序博客网 时间:2024/06/06 09:12

Python字符串替换有两种方法:

1. 使用字符串本身的方法

2. 正则表达式

Eg.

1.      str=”fuck world”

str.replace(‘world’,’python’,1) #1是替换次数

2.       import re

strinfo=re.compile(‘world’)

b=strinfo.sub(‘python’,str)

print b

3.      import re

file1=open(‘c:/test.txt’,’r’).read()

file1=re.sub(‘the’,’dpz’,file1)

file2=open(‘c:/test_after.txt’,’wb’)

file2.write(file1)

file2.close()

1 0