如何在python中从左到右替换文本文件中的字符?
我有一个文本文件 (*.txt),它的内容是"01110011",我想替换它:'00' ==> a, '01' ==> b, '10' ==> c,'11' ==> d 从左到右。所以内容变成'bdad'. 根据这篇文章,我使用了下面的代码,但不幸的是,替换不是定向的(我的意思是不是从左到右)。我可以请你帮助我吗?
# 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)
回答
只需构建一个新字符串,仅替换偶数 indeces 处的 2-char 子字符串:
repl = {
'00': 'a',
'01': 'b',
'10': 'c',
'11': 'd',
}
filedata = ''.join(repl[filedata[i:i+2]] for i in range(0, len(filedata), 2))