python 字符串替换
字符串替换可以用内置的方法和正则表达式完成。
1用字符串本身的replace方法:
a = 'hello word'
b = a.replace('word','python')
print b
例子:
#encoding=utf-8
# Created by double lin at 2018/8/7
# 获取小说“花千骨”
import urllib2
import re
if __name__ == '__main__':
url = 'http://www.136book.com/huaqiangu/'
head = {}
head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
req = urllib2.Request(url, headers=head)
response = urllib2.urlopen(req)
html = response.read()
# print html
url_name = re.findall(r'<li><a href="(.+?)">(.+?)</a></li>', html, re.S)
f = open('hello.txt', 'w')
for i in range(len(url_name)):
print url_name[i][0],
print url_name[i][1]
url = url_name[i][0]
name = url_name[i][1]
if url != '\n':
req = urllib2.Request(url,headers=head)
r =urllib2.urlopen(req)
# print r.read()
html1 = r.read()
content = re.findall(r'<br /><p>(.+?)</p><br />', html1, re.S)
for i in range(len(content)):
# print type(content[i])
f.write(name+'\n\n')
content[i] = content[i].replace('</p><p>', '\n')
# print content[i]
f.write(content[i]+'\n\n')
f.close()
2用正则表达式来完成替换:
import re
a = 'hello word'
strinfo = re.compile('word')
b = strinfo.sub('python',a)
print b