有一个文本文件,每一行中有多个\符号,现要把最后一个替换成空格,该如何实现?
如:
a\b\ccc\ddd
xxx\y\zzz
q\w
替换后:
a\b\ccc ddd
xxx\y zzz
q w
python代ç ç¼ç¨ä¸ç¨re模åéè¿æ£åå¹é çæ¹å¼ï¼æ¿æ¢ä¸ä¸ªå符串çæåä¸ä¸ªå符ï¼ä»£ç å¦ä¸ï¼
import re//ç¨Xæ¿æ¢åé¢çabc
replace_reg = re.compile(r'abc$')
print replace_reg.sub('X', '123abc')
#è¿è¡ç»æï¼'123X'
温馨提示:答案为网友推荐,仅供参考
第1个回答 推荐于2018-02-09
def rep_split(infile,spliter,repter):
with open(infile,'r') as sp_file:
for line in sp_file:
newline=line[::-1].replace(spliter,repter,1)[::-1]
print(newline)
#open('out.txt','a').writelines(outline)
rep_split('1kk.txt','\\',' ')
函数参数说明:第一个为输入文件,第二个为需要替换的,第三个为目标替换符号
效果如下
>>>
a\b\ccc ddd
xxx\y zzz
q w本回答被网友采纳
with open(infile,'r') as sp_file:
for line in sp_file:
newline=line[::-1].replace(spliter,repter,1)[::-1]
print(newline)
#open('out.txt','a').writelines(outline)
rep_split('1kk.txt','\\',' ')
函数参数说明:第一个为输入文件,第二个为需要替换的,第三个为目标替换符号
效果如下
>>>
a\b\ccc ddd
xxx\y zzz
q w本回答被网友采纳
第2个回答 2013-05-30
>>> spliter = '\\'
>>> for ln in content.splitlines():
... x = ln.split(spliter)
... print spliter.join(x[:-1]), x[-1]
...
a\b\ccc ddd
xxx\y zzz
q w
>>>
>>> for ln in content.splitlines():
... x = ln.split(spliter)
... print spliter.join(x[:-1]), x[-1]
...
a\b\ccc ddd
xxx\y zzz
q w
>>>
第3个回答 2013-05-30
def myreplace(s):
index = s.rfind("\\")
if index != -1:
s = s[:index]+" "+s[index+1:]
return s
text = open("yourfilename","r")
content = text.readlines()
text.close()
for name in content:
(four space here)print myreplace(name)
index = s.rfind("\\")
if index != -1:
s = s[:index]+" "+s[index+1:]
return s
text = open("yourfilename","r")
content = text.readlines()
text.close()
for name in content:
(four space here)print myreplace(name)