【python】字符串的替换

test====》
aaa
bbb
ccc
ddd
1.正则
import re
a = open('/root/test','r+')
f = a.readlines()
a.close()
for line in f:
b = re.sub('ddd','111',line.strip('\n'))
print b
*************************************************************
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os, re
FILE1 = open('file.txt', 'r')
file_content = FILE1.read()
FILE1.close()
print file_content
file_content = re.sub(r'bbb', 'eee', file_content)
FILE2 = open('file.txt', 'w')
FILE2.write(file_content)
FILE2.close()
##############################################
2. 列表替换
a=['aaa','bbb','ccc','ddd','eee','fff']
'---'.join(a).replace('bbb','eee').split('---')
['aaa','eee','ccc',ddd'','eee','fff']
本文来源 我爱IT技术网 http://www.52ij.com/jishu/664.html 转载请保留链接。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
