最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【整理】Python中,关于字符串的查找并替换

Python re crifan 4969浏览 0评论

关于如何替换,参考这里:
http://www.cnpythoner.com/post/65.html
解释有两种:
(1)用字符串本身的replace方法

a = 'hello word';
a.replace('word','python');

输出的结果是hello python。

(2)用正则来替换字符串

import re;
strinfo = re.compile('word');
b = strinfo.sub('python',a);
print b;

输出的结果也是hello python

但是,我此处,不知道何种原因,上述第一种方法,即用字符本身的replace方面,尝试了多遍,无论如何都实现不了字符串的替换。

后来无奈,只有用第二种方法,来实现字符串替换:

<p># replace old url with new url:
old_pic_url = &quot;http://hiphotos.baidu.com/&quot; + gBaiduBlogUser + r'/[a-z]{0,2}pic/item'
new_pic_url = gWordpressRootPath + &quot;wp-content/uploads/&quot; + gBaiduBlogUser + &quot;/pic&quot;
pattern = re.compile(old_pic_url)
blogContent = pattern.sub(new_pic_url, blogContent)</p>

转载请注明:在路上 » 【整理】Python中,关于字符串的查找并替换

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

  1. a = a.replace('hello', 'word')
    keroro52010年前 (2014-09-17)回复
85 queries in 0.169 seconds, using 22.05MB memory