如果你要用python匹配字符串的開頭或末尾是否包含一個字符串,就可以用startswith,和endswith
比如:content = 'ilovepython'
如果字符串content以ilove開始,返回True,否則返回False
content.startswith("ilove")
返回true
content.startswith("sss")
返回false
如果字符串content以python結尾,返回True,否則返回False
content.endswith('python')
返回true
content.endswith("sss")
返回false
下面這個例子是我寫了個文件替換的小程序。替換所有.html文件里的圖片的路徑
import os
import re
t = re.compile(r'\/?static\/|\/?media\/') #re.compile
template = '/home/laowangpython/'
for root, dirs, files in os.walk(template):
for f in files:
if f.endswith('.html'):
tihuan = 'http://www.cnpythoner.com/'
filename = '%s'%(os.path.join(root,f))
print filename
f_a = file(filename,'r')
info = []
for i in f_a:
content = t.sub(tihuan,i)
info.append(content)
finfo = "".join(info)
b = file(filename,'w')
b.write(finfo)
原創文章:http://www.cnpythoner.com/post/17.html,轉載請保留,謝謝!