python字符串替换的2种方法

python字符串替换可以用两种方法实现:

1.用字符串本身的方法

2.用正则来替换字符串

下面用个例子来实验:

a = 'hello word'

我把a字符串里的word替换为python 

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

a.replace('word' , 'python')

输出结果是hello  python

2.用正则表达式来完成替换:

import  re

strinfo = re . compile('word')

b = strinfo.sub('python',a)

printf (b)

输出结果也是hello  python

猜你喜欢

转载自www.cnblogs.com/cnn-ljc/p/12636227.html
今日推荐