我有一个 data.txt 文件,其中包含以下行:
this is sample {data1}
this one is {data2}
again {data1}
我有这段代码,可以将文件的每一行读取到一个列表中并打印出来:
data1 = 'line 1'
data2 = 'line 2'
with open('data.txt') as file:
lines = file.read().splitlines()
print(lines)
输出结果为:
['this is sample {data1}', 'this one is {data2}', 'again {data1}']
现在,我该如何用它们的值替换变量并使其变为以下形式:
['this is sample line 1', 'this one is line 2', 'again line 1']