ITPub博客

首页 > 应用开发 > IT综合 > python 字符串替换可以用2种方法实现:

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

IT综合 作者:studywell 时间:2016-11-02 20:43:15 0 删除 编辑
转自:http://blog.sina.com.cn/s/blog_71f389090100vft4.html

python 字符串替换可以用2种方法实现:
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)
print b
输出的结果也是hello python

至于用哪个方法的话,看你自己的选择了。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29519108/viewspace-2127546/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2014-03-04

  • 博文量
    307
  • 访问量
    535421