我有一个文本文件(*.txt),它的内容是"01110011"
,我想替换它:'00' ==> a
,'01' ==> b
,'10' ==> c
,'11' ==> d
从左到右。因此内容变成'bdad'
。
根据this post,我使用了下面的代码,但不幸的是,替换不是定向的(我的意思是它不是从左到右)。
我可以请你帮我吗
# Read in the file
with open('file.txt', 'r') as file :
filedata = file.read()
# Replace the target string
filedata = filedata.replace('00', 'a')
filedata = filedata.replace('01', 'b')
filedata = filedata.replace('10', 'c')
filedata = filedata.replace('11', 'd')
# Write the file out again
with open('file.txt', 'w') as file:
file.write(filedata)
这将有助于:
只需构建一个新字符串,仅替换偶数索引处的2字符子字符串:
省略文件处理,您可以执行以下操作:-
相关问题 更多 >
编程相关推荐