为什么即使已经添加了模式、repl 和字符串,re.sub 也会替换出现的 none

why does re.sub replaces none of the occurrences even there is already pattern, repl and string added

a.txt 是一个包含以下字符串的文件:

g g abc
abc
457625

er
oldstring = "abc"
newstring = "def"
with open('a.txt', 'r') as f:
       data = f.read()
       re.sub(r"\b{}\b".format(oldstring), r"\b{}\b".format(newstring), data)
with open('b.txt', 'w') as out:
       out.write(data)

有了这个 python 代码,我想我最终可以得到 b.txt 我可以把“abc”变成“def”。令人惊讶的是,我得到了与 a.txt.

中完全相同的字符串

谁能告诉我我的代码哪里出错了?

您需要将 re.sub 的输出分配回原始变量。

   data = re.sub(r"\b{}\b".format(oldstring), newstring, data)